module.audio.mp3.php 97 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022
  1. <?php
  2. /////////////////////////////////////////////////////////////////
  3. /// getID3() by James Heinrich <info@getid3.org> //
  4. // available at http://getid3.sourceforge.net //
  5. // or http://www.getid3.org //
  6. // also https://github.com/JamesHeinrich/getID3 //
  7. /////////////////////////////////////////////////////////////////
  8. // See readme.txt for more details //
  9. /////////////////////////////////////////////////////////////////
  10. // //
  11. // module.audio.mp3.php //
  12. // module for analyzing MP3 files //
  13. // dependencies: NONE //
  14. // ///
  15. /////////////////////////////////////////////////////////////////
  16. // number of frames to scan to determine if MPEG-audio sequence is valid
  17. // Lower this number to 5-20 for faster scanning
  18. // Increase this number to 50+ for most accurate detection of valid VBR/CBR
  19. // mpeg-audio streams
  20. define('GETID3_MP3_VALID_CHECK_FRAMES', 35);
  21. class getid3_mp3 extends getid3_handler
  22. {
  23. public $allow_bruteforce = false; // forces getID3() to scan the file byte-by-byte and log all the valid audio frame headers - extremely slow, unrecommended, but may provide data from otherwise-unusuable files
  24. public function Analyze() {
  25. $info = &$this->getid3->info;
  26. $initialOffset = $info['avdataoffset'];
  27. if (!$this->getOnlyMPEGaudioInfo($info['avdataoffset'])) {
  28. if ($this->allow_bruteforce) {
  29. $info['error'][] = 'Rescanning file in BruteForce mode';
  30. $this->getOnlyMPEGaudioInfoBruteForce($this->getid3->fp, $info);
  31. }
  32. }
  33. if (isset($info['mpeg']['audio']['bitrate_mode'])) {
  34. $info['audio']['bitrate_mode'] = strtolower($info['mpeg']['audio']['bitrate_mode']);
  35. }
  36. if (((isset($info['id3v2']['headerlength']) && ($info['avdataoffset'] > $info['id3v2']['headerlength'])) || (!isset($info['id3v2']) && ($info['avdataoffset'] > 0) && ($info['avdataoffset'] != $initialOffset)))) {
  37. $synchoffsetwarning = 'Unknown data before synch ';
  38. if (isset($info['id3v2']['headerlength'])) {
  39. $synchoffsetwarning .= '(ID3v2 header ends at '.$info['id3v2']['headerlength'].', then '.($info['avdataoffset'] - $info['id3v2']['headerlength']).' bytes garbage, ';
  40. } elseif ($initialOffset > 0) {
  41. $synchoffsetwarning .= '(should be at '.$initialOffset.', ';
  42. } else {
  43. $synchoffsetwarning .= '(should be at beginning of file, ';
  44. }
  45. $synchoffsetwarning .= 'synch detected at '.$info['avdataoffset'].')';
  46. if (isset($info['audio']['bitrate_mode']) && ($info['audio']['bitrate_mode'] == 'cbr')) {
  47. if (!empty($info['id3v2']['headerlength']) && (($info['avdataoffset'] - $info['id3v2']['headerlength']) == $info['mpeg']['audio']['framelength'])) {
  48. $synchoffsetwarning .= '. This is a known problem with some versions of LAME (3.90-3.92) DLL in CBR mode.';
  49. $info['audio']['codec'] = 'LAME';
  50. $CurrentDataLAMEversionString = 'LAME3.';
  51. } elseif (empty($info['id3v2']['headerlength']) && ($info['avdataoffset'] == $info['mpeg']['audio']['framelength'])) {
  52. $synchoffsetwarning .= '. This is a known problem with some versions of LAME (3.90 - 3.92) DLL in CBR mode.';
  53. $info['audio']['codec'] = 'LAME';
  54. $CurrentDataLAMEversionString = 'LAME3.';
  55. }
  56. }
  57. $info['warning'][] = $synchoffsetwarning;
  58. }
  59. if (isset($info['mpeg']['audio']['LAME'])) {
  60. $info['audio']['codec'] = 'LAME';
  61. if (!empty($info['mpeg']['audio']['LAME']['long_version'])) {
  62. $info['audio']['encoder'] = rtrim($info['mpeg']['audio']['LAME']['long_version'], "\x00");
  63. } elseif (!empty($info['mpeg']['audio']['LAME']['short_version'])) {
  64. $info['audio']['encoder'] = rtrim($info['mpeg']['audio']['LAME']['short_version'], "\x00");
  65. }
  66. }
  67. $CurrentDataLAMEversionString = (!empty($CurrentDataLAMEversionString) ? $CurrentDataLAMEversionString : (isset($info['audio']['encoder']) ? $info['audio']['encoder'] : ''));
  68. if (!empty($CurrentDataLAMEversionString) && (substr($CurrentDataLAMEversionString, 0, 6) == 'LAME3.') && !preg_match('[0-9\)]', substr($CurrentDataLAMEversionString, -1))) {
  69. // a version number of LAME that does not end with a number like "LAME3.92"
  70. // or with a closing parenthesis like "LAME3.88 (alpha)"
  71. // or a version of LAME with the LAMEtag-not-filled-in-DLL-mode bug (3.90-3.92)
  72. // not sure what the actual last frame length will be, but will be less than or equal to 1441
  73. $PossiblyLongerLAMEversion_FrameLength = 1441;
  74. // Not sure what version of LAME this is - look in padding of last frame for longer version string
  75. $PossibleLAMEversionStringOffset = $info['avdataend'] - $PossiblyLongerLAMEversion_FrameLength;
  76. $this->fseek($PossibleLAMEversionStringOffset);
  77. $PossiblyLongerLAMEversion_Data = $this->fread($PossiblyLongerLAMEversion_FrameLength);
  78. switch (substr($CurrentDataLAMEversionString, -1)) {
  79. case 'a':
  80. case 'b':
  81. // "LAME3.94a" will have a longer version string of "LAME3.94 (alpha)" for example
  82. // need to trim off "a" to match longer string
  83. $CurrentDataLAMEversionString = substr($CurrentDataLAMEversionString, 0, -1);
  84. break;
  85. }
  86. if (($PossiblyLongerLAMEversion_String = strstr($PossiblyLongerLAMEversion_Data, $CurrentDataLAMEversionString)) !== false) {
  87. if (substr($PossiblyLongerLAMEversion_String, 0, strlen($CurrentDataLAMEversionString)) == $CurrentDataLAMEversionString) {
  88. $PossiblyLongerLAMEversion_NewString = substr($PossiblyLongerLAMEversion_String, 0, strspn($PossiblyLongerLAMEversion_String, 'LAME0123456789., (abcdefghijklmnopqrstuvwxyzJFSOND)')); //"LAME3.90.3" "LAME3.87 (beta 1, Sep 27 2000)" "LAME3.88 (beta)"
  89. if (empty($info['audio']['encoder']) || (strlen($PossiblyLongerLAMEversion_NewString) > strlen($info['audio']['encoder']))) {
  90. $info['audio']['encoder'] = $PossiblyLongerLAMEversion_NewString;
  91. }
  92. }
  93. }
  94. }
  95. if (!empty($info['audio']['encoder'])) {
  96. $info['audio']['encoder'] = rtrim($info['audio']['encoder'], "\x00 ");
  97. }
  98. switch (isset($info['mpeg']['audio']['layer']) ? $info['mpeg']['audio']['layer'] : '') {
  99. case 1:
  100. case 2:
  101. $info['audio']['dataformat'] = 'mp'.$info['mpeg']['audio']['layer'];
  102. break;
  103. }
  104. if (isset($info['fileformat']) && ($info['fileformat'] == 'mp3')) {
  105. switch ($info['audio']['dataformat']) {
  106. case 'mp1':
  107. case 'mp2':
  108. case 'mp3':
  109. $info['fileformat'] = $info['audio']['dataformat'];
  110. break;
  111. default:
  112. $info['warning'][] = 'Expecting [audio][dataformat] to be mp1/mp2/mp3 when fileformat == mp3, [audio][dataformat] actually "'.$info['audio']['dataformat'].'"';
  113. break;
  114. }
  115. }
  116. if (empty($info['fileformat'])) {
  117. unset($info['fileformat']);
  118. unset($info['audio']['bitrate_mode']);
  119. unset($info['avdataoffset']);
  120. unset($info['avdataend']);
  121. return false;
  122. }
  123. $info['mime_type'] = 'audio/mpeg';
  124. $info['audio']['lossless'] = false;
  125. // Calculate playtime
  126. if (!isset($info['playtime_seconds']) && isset($info['audio']['bitrate']) && ($info['audio']['bitrate'] > 0)) {
  127. $info['playtime_seconds'] = ($info['avdataend'] - $info['avdataoffset']) * 8 / $info['audio']['bitrate'];
  128. }
  129. $info['audio']['encoder_options'] = $this->GuessEncoderOptions();
  130. return true;
  131. }
  132. public function GuessEncoderOptions() {
  133. // shortcuts
  134. $info = &$this->getid3->info;
  135. if (!empty($info['mpeg']['audio'])) {
  136. $thisfile_mpeg_audio = &$info['mpeg']['audio'];
  137. if (!empty($thisfile_mpeg_audio['LAME'])) {
  138. $thisfile_mpeg_audio_lame = &$thisfile_mpeg_audio['LAME'];
  139. }
  140. }
  141. $encoder_options = '';
  142. static $NamedPresetBitrates = array(16, 24, 40, 56, 112, 128, 160, 192, 256);
  143. if (isset($thisfile_mpeg_audio['VBR_method']) && ($thisfile_mpeg_audio['VBR_method'] == 'Fraunhofer') && !empty($thisfile_mpeg_audio['VBR_quality'])) {
  144. $encoder_options = 'VBR q'.$thisfile_mpeg_audio['VBR_quality'];
  145. } elseif (!empty($thisfile_mpeg_audio_lame['preset_used']) && (!in_array($thisfile_mpeg_audio_lame['preset_used_id'], $NamedPresetBitrates))) {
  146. $encoder_options = $thisfile_mpeg_audio_lame['preset_used'];
  147. } elseif (!empty($thisfile_mpeg_audio_lame['vbr_quality'])) {
  148. static $KnownEncoderValues = array();
  149. if (empty($KnownEncoderValues)) {
  150. //$KnownEncoderValues[abrbitrate_minbitrate][vbr_quality][raw_vbr_method][raw_noise_shaping][raw_stereo_mode][ath_type][lowpass_frequency] = 'preset name';
  151. $KnownEncoderValues[0xFF][58][1][1][3][2][20500] = '--alt-preset insane'; // 3.90, 3.90.1, 3.92
  152. $KnownEncoderValues[0xFF][58][1][1][3][2][20600] = '--alt-preset insane'; // 3.90.2, 3.90.3, 3.91
  153. $KnownEncoderValues[0xFF][57][1][1][3][4][20500] = '--alt-preset insane'; // 3.94, 3.95
  154. $KnownEncoderValues['**'][78][3][2][3][2][19500] = '--alt-preset extreme'; // 3.90, 3.90.1, 3.92
  155. $KnownEncoderValues['**'][78][3][2][3][2][19600] = '--alt-preset extreme'; // 3.90.2, 3.91
  156. $KnownEncoderValues['**'][78][3][1][3][2][19600] = '--alt-preset extreme'; // 3.90.3
  157. $KnownEncoderValues['**'][78][4][2][3][2][19500] = '--alt-preset fast extreme'; // 3.90, 3.90.1, 3.92
  158. $KnownEncoderValues['**'][78][4][2][3][2][19600] = '--alt-preset fast extreme'; // 3.90.2, 3.90.3, 3.91
  159. $KnownEncoderValues['**'][78][3][2][3][4][19000] = '--alt-preset standard'; // 3.90, 3.90.1, 3.90.2, 3.91, 3.92
  160. $KnownEncoderValues['**'][78][3][1][3][4][19000] = '--alt-preset standard'; // 3.90.3
  161. $KnownEncoderValues['**'][78][4][2][3][4][19000] = '--alt-preset fast standard'; // 3.90, 3.90.1, 3.90.2, 3.91, 3.92
  162. $KnownEncoderValues['**'][78][4][1][3][4][19000] = '--alt-preset fast standard'; // 3.90.3
  163. $KnownEncoderValues['**'][88][4][1][3][3][19500] = '--r3mix'; // 3.90, 3.90.1, 3.92
  164. $KnownEncoderValues['**'][88][4][1][3][3][19600] = '--r3mix'; // 3.90.2, 3.90.3, 3.91
  165. $KnownEncoderValues['**'][67][4][1][3][4][18000] = '--r3mix'; // 3.94, 3.95
  166. $KnownEncoderValues['**'][68][3][2][3][4][18000] = '--alt-preset medium'; // 3.90.3
  167. $KnownEncoderValues['**'][68][4][2][3][4][18000] = '--alt-preset fast medium'; // 3.90.3
  168. $KnownEncoderValues[0xFF][99][1][1][1][2][0] = '--preset studio'; // 3.90, 3.90.1, 3.90.2, 3.91, 3.92
  169. $KnownEncoderValues[0xFF][58][2][1][3][2][20600] = '--preset studio'; // 3.90.3, 3.93.1
  170. $KnownEncoderValues[0xFF][58][2][1][3][2][20500] = '--preset studio'; // 3.93
  171. $KnownEncoderValues[0xFF][57][2][1][3][4][20500] = '--preset studio'; // 3.94, 3.95
  172. $KnownEncoderValues[0xC0][88][1][1][1][2][0] = '--preset cd'; // 3.90, 3.90.1, 3.90.2, 3.91, 3.92
  173. $KnownEncoderValues[0xC0][58][2][2][3][2][19600] = '--preset cd'; // 3.90.3, 3.93.1
  174. $KnownEncoderValues[0xC0][58][2][2][3][2][19500] = '--preset cd'; // 3.93
  175. $KnownEncoderValues[0xC0][57][2][1][3][4][19500] = '--preset cd'; // 3.94, 3.95
  176. $KnownEncoderValues[0xA0][78][1][1][3][2][18000] = '--preset hifi'; // 3.90, 3.90.1, 3.90.2, 3.91, 3.92
  177. $KnownEncoderValues[0xA0][58][2][2][3][2][18000] = '--preset hifi'; // 3.90.3, 3.93, 3.93.1
  178. $KnownEncoderValues[0xA0][57][2][1][3][4][18000] = '--preset hifi'; // 3.94, 3.95
  179. $KnownEncoderValues[0x80][67][1][1][3][2][18000] = '--preset tape'; // 3.90, 3.90.1, 3.90.2, 3.91, 3.92
  180. $KnownEncoderValues[0x80][67][1][1][3][2][15000] = '--preset radio'; // 3.90, 3.90.1, 3.90.2, 3.91, 3.92
  181. $KnownEncoderValues[0x70][67][1][1][3][2][15000] = '--preset fm'; // 3.90, 3.90.1, 3.90.2, 3.91, 3.92
  182. $KnownEncoderValues[0x70][58][2][2][3][2][16000] = '--preset tape/radio/fm'; // 3.90.3, 3.93, 3.93.1
  183. $KnownEncoderValues[0x70][57][2][1][3][4][16000] = '--preset tape/radio/fm'; // 3.94, 3.95
  184. $KnownEncoderValues[0x38][58][2][2][0][2][10000] = '--preset voice'; // 3.90.3, 3.93, 3.93.1
  185. $KnownEncoderValues[0x38][57][2][1][0][4][15000] = '--preset voice'; // 3.94, 3.95
  186. $KnownEncoderValues[0x38][57][2][1][0][4][16000] = '--preset voice'; // 3.94a14
  187. $KnownEncoderValues[0x28][65][1][1][0][2][7500] = '--preset mw-us'; // 3.90, 3.90.1, 3.92
  188. $KnownEncoderValues[0x28][65][1][1][0][2][7600] = '--preset mw-us'; // 3.90.2, 3.91
  189. $KnownEncoderValues[0x28][58][2][2][0][2][7000] = '--preset mw-us'; // 3.90.3, 3.93, 3.93.1
  190. $KnownEncoderValues[0x28][57][2][1][0][4][10500] = '--preset mw-us'; // 3.94, 3.95
  191. $KnownEncoderValues[0x28][57][2][1][0][4][11200] = '--preset mw-us'; // 3.94a14
  192. $KnownEncoderValues[0x28][57][2][1][0][4][8800] = '--preset mw-us'; // 3.94a15
  193. $KnownEncoderValues[0x18][58][2][2][0][2][4000] = '--preset phon+/lw/mw-eu/sw'; // 3.90.3, 3.93.1
  194. $KnownEncoderValues[0x18][58][2][2][0][2][3900] = '--preset phon+/lw/mw-eu/sw'; // 3.93
  195. $KnownEncoderValues[0x18][57][2][1][0][4][5900] = '--preset phon+/lw/mw-eu/sw'; // 3.94, 3.95
  196. $KnownEncoderValues[0x18][57][2][1][0][4][6200] = '--preset phon+/lw/mw-eu/sw'; // 3.94a14
  197. $KnownEncoderValues[0x18][57][2][1][0][4][3200] = '--preset phon+/lw/mw-eu/sw'; // 3.94a15
  198. $KnownEncoderValues[0x10][58][2][2][0][2][3800] = '--preset phone'; // 3.90.3, 3.93.1
  199. $KnownEncoderValues[0x10][58][2][2][0][2][3700] = '--preset phone'; // 3.93
  200. $KnownEncoderValues[0x10][57][2][1][0][4][5600] = '--preset phone'; // 3.94, 3.95
  201. }
  202. if (isset($KnownEncoderValues[$thisfile_mpeg_audio_lame['raw']['abrbitrate_minbitrate']][$thisfile_mpeg_audio_lame['vbr_quality']][$thisfile_mpeg_audio_lame['raw']['vbr_method']][$thisfile_mpeg_audio_lame['raw']['noise_shaping']][$thisfile_mpeg_audio_lame['raw']['stereo_mode']][$thisfile_mpeg_audio_lame['ath_type']][$thisfile_mpeg_audio_lame['lowpass_frequency']])) {
  203. $encoder_options = $KnownEncoderValues[$thisfile_mpeg_audio_lame['raw']['abrbitrate_minbitrate']][$thisfile_mpeg_audio_lame['vbr_quality']][$thisfile_mpeg_audio_lame['raw']['vbr_method']][$thisfile_mpeg_audio_lame['raw']['noise_shaping']][$thisfile_mpeg_audio_lame['raw']['stereo_mode']][$thisfile_mpeg_audio_lame['ath_type']][$thisfile_mpeg_audio_lame['lowpass_frequency']];
  204. } elseif (isset($KnownEncoderValues['**'][$thisfile_mpeg_audio_lame['vbr_quality']][$thisfile_mpeg_audio_lame['raw']['vbr_method']][$thisfile_mpeg_audio_lame['raw']['noise_shaping']][$thisfile_mpeg_audio_lame['raw']['stereo_mode']][$thisfile_mpeg_audio_lame['ath_type']][$thisfile_mpeg_audio_lame['lowpass_frequency']])) {
  205. $encoder_options = $KnownEncoderValues['**'][$thisfile_mpeg_audio_lame['vbr_quality']][$thisfile_mpeg_audio_lame['raw']['vbr_method']][$thisfile_mpeg_audio_lame['raw']['noise_shaping']][$thisfile_mpeg_audio_lame['raw']['stereo_mode']][$thisfile_mpeg_audio_lame['ath_type']][$thisfile_mpeg_audio_lame['lowpass_frequency']];
  206. } elseif ($info['audio']['bitrate_mode'] == 'vbr') {
  207. // http://gabriel.mp3-tech.org/mp3infotag.html
  208. // int Quality = (100 - 10 * gfp->VBR_q - gfp->quality)h
  209. $LAME_V_value = 10 - ceil($thisfile_mpeg_audio_lame['vbr_quality'] / 10);
  210. $LAME_q_value = 100 - $thisfile_mpeg_audio_lame['vbr_quality'] - ($LAME_V_value * 10);
  211. $encoder_options = '-V'.$LAME_V_value.' -q'.$LAME_q_value;
  212. } elseif ($info['audio']['bitrate_mode'] == 'cbr') {
  213. $encoder_options = strtoupper($info['audio']['bitrate_mode']).ceil($info['audio']['bitrate'] / 1000);
  214. } else {
  215. $encoder_options = strtoupper($info['audio']['bitrate_mode']);
  216. }
  217. } elseif (!empty($thisfile_mpeg_audio_lame['bitrate_abr'])) {
  218. $encoder_options = 'ABR'.$thisfile_mpeg_audio_lame['bitrate_abr'];
  219. } elseif (!empty($info['audio']['bitrate'])) {
  220. if ($info['audio']['bitrate_mode'] == 'cbr') {
  221. $encoder_options = strtoupper($info['audio']['bitrate_mode']).ceil($info['audio']['bitrate'] / 1000);
  222. } else {
  223. $encoder_options = strtoupper($info['audio']['bitrate_mode']);
  224. }
  225. }
  226. if (!empty($thisfile_mpeg_audio_lame['bitrate_min'])) {
  227. $encoder_options .= ' -b'.$thisfile_mpeg_audio_lame['bitrate_min'];
  228. }
  229. if (!empty($thisfile_mpeg_audio_lame['encoding_flags']['nogap_prev']) || !empty($thisfile_mpeg_audio_lame['encoding_flags']['nogap_next'])) {
  230. $encoder_options .= ' --nogap';
  231. }
  232. if (!empty($thisfile_mpeg_audio_lame['lowpass_frequency'])) {
  233. $ExplodedOptions = explode(' ', $encoder_options, 4);
  234. if ($ExplodedOptions[0] == '--r3mix') {
  235. $ExplodedOptions[1] = 'r3mix';
  236. }
  237. switch ($ExplodedOptions[0]) {
  238. case '--preset':
  239. case '--alt-preset':
  240. case '--r3mix':
  241. if ($ExplodedOptions[1] == 'fast') {
  242. $ExplodedOptions[1] .= ' '.$ExplodedOptions[2];
  243. }
  244. switch ($ExplodedOptions[1]) {
  245. case 'portable':
  246. case 'medium':
  247. case 'standard':
  248. case 'extreme':
  249. case 'insane':
  250. case 'fast portable':
  251. case 'fast medium':
  252. case 'fast standard':
  253. case 'fast extreme':
  254. case 'fast insane':
  255. case 'r3mix':
  256. static $ExpectedLowpass = array(
  257. 'insane|20500' => 20500,
  258. 'insane|20600' => 20600, // 3.90.2, 3.90.3, 3.91
  259. 'medium|18000' => 18000,
  260. 'fast medium|18000' => 18000,
  261. 'extreme|19500' => 19500, // 3.90, 3.90.1, 3.92, 3.95
  262. 'extreme|19600' => 19600, // 3.90.2, 3.90.3, 3.91, 3.93.1
  263. 'fast extreme|19500' => 19500, // 3.90, 3.90.1, 3.92, 3.95
  264. 'fast extreme|19600' => 19600, // 3.90.2, 3.90.3, 3.91, 3.93.1
  265. 'standard|19000' => 19000,
  266. 'fast standard|19000' => 19000,
  267. 'r3mix|19500' => 19500, // 3.90, 3.90.1, 3.92
  268. 'r3mix|19600' => 19600, // 3.90.2, 3.90.3, 3.91
  269. 'r3mix|18000' => 18000, // 3.94, 3.95
  270. );
  271. if (!isset($ExpectedLowpass[$ExplodedOptions[1].'|'.$thisfile_mpeg_audio_lame['lowpass_frequency']]) && ($thisfile_mpeg_audio_lame['lowpass_frequency'] < 22050) && (round($thisfile_mpeg_audio_lame['lowpass_frequency'] / 1000) < round($thisfile_mpeg_audio['sample_rate'] / 2000))) {
  272. $encoder_options .= ' --lowpass '.$thisfile_mpeg_audio_lame['lowpass_frequency'];
  273. }
  274. break;
  275. default:
  276. break;
  277. }
  278. break;
  279. }
  280. }
  281. if (isset($thisfile_mpeg_audio_lame['raw']['source_sample_freq'])) {
  282. if (($thisfile_mpeg_audio['sample_rate'] == 44100) && ($thisfile_mpeg_audio_lame['raw']['source_sample_freq'] != 1)) {
  283. $encoder_options .= ' --resample 44100';
  284. } elseif (($thisfile_mpeg_audio['sample_rate'] == 48000) && ($thisfile_mpeg_audio_lame['raw']['source_sample_freq'] != 2)) {
  285. $encoder_options .= ' --resample 48000';
  286. } elseif ($thisfile_mpeg_audio['sample_rate'] < 44100) {
  287. switch ($thisfile_mpeg_audio_lame['raw']['source_sample_freq']) {
  288. case 0: // <= 32000
  289. // may or may not be same as source frequency - ignore
  290. break;
  291. case 1: // 44100
  292. case 2: // 48000
  293. case 3: // 48000+
  294. $ExplodedOptions = explode(' ', $encoder_options, 4);
  295. switch ($ExplodedOptions[0]) {
  296. case '--preset':
  297. case '--alt-preset':
  298. switch ($ExplodedOptions[1]) {
  299. case 'fast':
  300. case 'portable':
  301. case 'medium':
  302. case 'standard':
  303. case 'extreme':
  304. case 'insane':
  305. $encoder_options .= ' --resample '.$thisfile_mpeg_audio['sample_rate'];
  306. break;
  307. default:
  308. static $ExpectedResampledRate = array(
  309. 'phon+/lw/mw-eu/sw|16000' => 16000,
  310. 'mw-us|24000' => 24000, // 3.95
  311. 'mw-us|32000' => 32000, // 3.93
  312. 'mw-us|16000' => 16000, // 3.92
  313. 'phone|16000' => 16000,
  314. 'phone|11025' => 11025, // 3.94a15
  315. 'radio|32000' => 32000, // 3.94a15
  316. 'fm/radio|32000' => 32000, // 3.92
  317. 'fm|32000' => 32000, // 3.90
  318. 'voice|32000' => 32000);
  319. if (!isset($ExpectedResampledRate[$ExplodedOptions[1].'|'.$thisfile_mpeg_audio['sample_rate']])) {
  320. $encoder_options .= ' --resample '.$thisfile_mpeg_audio['sample_rate'];
  321. }
  322. break;
  323. }
  324. break;
  325. case '--r3mix':
  326. default:
  327. $encoder_options .= ' --resample '.$thisfile_mpeg_audio['sample_rate'];
  328. break;
  329. }
  330. break;
  331. }
  332. }
  333. }
  334. if (empty($encoder_options) && !empty($info['audio']['bitrate']) && !empty($info['audio']['bitrate_mode'])) {
  335. //$encoder_options = strtoupper($info['audio']['bitrate_mode']).ceil($info['audio']['bitrate'] / 1000);
  336. $encoder_options = strtoupper($info['audio']['bitrate_mode']);
  337. }
  338. return $encoder_options;
  339. }
  340. public function decodeMPEGaudioHeader($offset, &$info, $recursivesearch=true, $ScanAsCBR=false, $FastMPEGheaderScan=false) {
  341. static $MPEGaudioVersionLookup;
  342. static $MPEGaudioLayerLookup;
  343. static $MPEGaudioBitrateLookup;
  344. static $MPEGaudioFrequencyLookup;
  345. static $MPEGaudioChannelModeLookup;
  346. static $MPEGaudioModeExtensionLookup;
  347. static $MPEGaudioEmphasisLookup;
  348. if (empty($MPEGaudioVersionLookup)) {
  349. $MPEGaudioVersionLookup = self::MPEGaudioVersionArray();
  350. $MPEGaudioLayerLookup = self::MPEGaudioLayerArray();
  351. $MPEGaudioBitrateLookup = self::MPEGaudioBitrateArray();
  352. $MPEGaudioFrequencyLookup = self::MPEGaudioFrequencyArray();
  353. $MPEGaudioChannelModeLookup = self::MPEGaudioChannelModeArray();
  354. $MPEGaudioModeExtensionLookup = self::MPEGaudioModeExtensionArray();
  355. $MPEGaudioEmphasisLookup = self::MPEGaudioEmphasisArray();
  356. }
  357. if ($this->fseek($offset) != 0) {
  358. $info['error'][] = 'decodeMPEGaudioHeader() failed to seek to next offset at '.$offset;
  359. return false;
  360. }
  361. //$headerstring = $this->fread(1441); // worst-case max length = 32kHz @ 320kbps layer 3 = 1441 bytes/frame
  362. $headerstring = $this->fread(226); // LAME header at offset 36 + 190 bytes of Xing/LAME data
  363. // MP3 audio frame structure:
  364. // $aa $aa $aa $aa [$bb $bb] $cc...
  365. // where $aa..$aa is the four-byte mpeg-audio header (below)
  366. // $bb $bb is the optional 2-byte CRC
  367. // and $cc... is the audio data
  368. $head4 = substr($headerstring, 0, 4);
  369. static $MPEGaudioHeaderDecodeCache = array();
  370. if (isset($MPEGaudioHeaderDecodeCache[$head4])) {
  371. $MPEGheaderRawArray = $MPEGaudioHeaderDecodeCache[$head4];
  372. } else {
  373. $MPEGheaderRawArray = self::MPEGaudioHeaderDecode($head4);
  374. $MPEGaudioHeaderDecodeCache[$head4] = $MPEGheaderRawArray;
  375. }
  376. static $MPEGaudioHeaderValidCache = array();
  377. if (!isset($MPEGaudioHeaderValidCache[$head4])) { // Not in cache
  378. //$MPEGaudioHeaderValidCache[$head4] = self::MPEGaudioHeaderValid($MPEGheaderRawArray, false, true); // allow badly-formatted freeformat (from LAME 3.90 - 3.93.1)
  379. $MPEGaudioHeaderValidCache[$head4] = self::MPEGaudioHeaderValid($MPEGheaderRawArray, false, false);
  380. }
  381. // shortcut
  382. if (!isset($info['mpeg']['audio'])) {
  383. $info['mpeg']['audio'] = array();
  384. }
  385. $thisfile_mpeg_audio = &$info['mpeg']['audio'];
  386. if ($MPEGaudioHeaderValidCache[$head4]) {
  387. $thisfile_mpeg_audio['raw'] = $MPEGheaderRawArray;
  388. } else {
  389. $info['error'][] = 'Invalid MPEG audio header ('.getid3_lib::PrintHexBytes($head4).') at offset '.$offset;
  390. return false;
  391. }
  392. if (!$FastMPEGheaderScan) {
  393. $thisfile_mpeg_audio['version'] = $MPEGaudioVersionLookup[$thisfile_mpeg_audio['raw']['version']];
  394. $thisfile_mpeg_audio['layer'] = $MPEGaudioLayerLookup[$thisfile_mpeg_audio['raw']['layer']];
  395. $thisfile_mpeg_audio['channelmode'] = $MPEGaudioChannelModeLookup[$thisfile_mpeg_audio['raw']['channelmode']];
  396. $thisfile_mpeg_audio['channels'] = (($thisfile_mpeg_audio['channelmode'] == 'mono') ? 1 : 2);
  397. $thisfile_mpeg_audio['sample_rate'] = $MPEGaudioFrequencyLookup[$thisfile_mpeg_audio['version']][$thisfile_mpeg_audio['raw']['sample_rate']];
  398. $thisfile_mpeg_audio['protection'] = !$thisfile_mpeg_audio['raw']['protection'];
  399. $thisfile_mpeg_audio['private'] = (bool) $thisfile_mpeg_audio['raw']['private'];
  400. $thisfile_mpeg_audio['modeextension'] = $MPEGaudioModeExtensionLookup[$thisfile_mpeg_audio['layer']][$thisfile_mpeg_audio['raw']['modeextension']];
  401. $thisfile_mpeg_audio['copyright'] = (bool) $thisfile_mpeg_audio['raw']['copyright'];
  402. $thisfile_mpeg_audio['original'] = (bool) $thisfile_mpeg_audio['raw']['original'];
  403. $thisfile_mpeg_audio['emphasis'] = $MPEGaudioEmphasisLookup[$thisfile_mpeg_audio['raw']['emphasis']];
  404. $info['audio']['channels'] = $thisfile_mpeg_audio['channels'];
  405. $info['audio']['sample_rate'] = $thisfile_mpeg_audio['sample_rate'];
  406. if ($thisfile_mpeg_audio['protection']) {
  407. $thisfile_mpeg_audio['crc'] = getid3_lib::BigEndian2Int(substr($headerstring, 4, 2));
  408. }
  409. }
  410. if ($thisfile_mpeg_audio['raw']['bitrate'] == 15) {
  411. // http://www.hydrogenaudio.org/?act=ST&f=16&t=9682&st=0
  412. $info['warning'][] = 'Invalid bitrate index (15), this is a known bug in free-format MP3s encoded by LAME v3.90 - 3.93.1';
  413. $thisfile_mpeg_audio['raw']['bitrate'] = 0;
  414. }
  415. $thisfile_mpeg_audio['padding'] = (bool) $thisfile_mpeg_audio['raw']['padding'];
  416. $thisfile_mpeg_audio['bitrate'] = $MPEGaudioBitrateLookup[$thisfile_mpeg_audio['version']][$thisfile_mpeg_audio['layer']][$thisfile_mpeg_audio['raw']['bitrate']];
  417. if (($thisfile_mpeg_audio['bitrate'] == 'free') && ($offset == $info['avdataoffset'])) {
  418. // only skip multiple frame check if free-format bitstream found at beginning of file
  419. // otherwise is quite possibly simply corrupted data
  420. $recursivesearch = false;
  421. }
  422. // For Layer 2 there are some combinations of bitrate and mode which are not allowed.
  423. if (!$FastMPEGheaderScan && ($thisfile_mpeg_audio['layer'] == '2')) {
  424. $info['audio']['dataformat'] = 'mp2';
  425. switch ($thisfile_mpeg_audio['channelmode']) {
  426. case 'mono':
  427. if (($thisfile_mpeg_audio['bitrate'] == 'free') || ($thisfile_mpeg_audio['bitrate'] <= 192000)) {
  428. // these are ok
  429. } else {
  430. $info['error'][] = $thisfile_mpeg_audio['bitrate'].'kbps not allowed in Layer 2, '.$thisfile_mpeg_audio['channelmode'].'.';
  431. return false;
  432. }
  433. break;
  434. case 'stereo':
  435. case 'joint stereo':
  436. case 'dual channel':
  437. if (($thisfile_mpeg_audio['bitrate'] == 'free') || ($thisfile_mpeg_audio['bitrate'] == 64000) || ($thisfile_mpeg_audio['bitrate'] >= 96000)) {
  438. // these are ok
  439. } else {
  440. $info['error'][] = intval(round($thisfile_mpeg_audio['bitrate'] / 1000)).'kbps not allowed in Layer 2, '.$thisfile_mpeg_audio['channelmode'].'.';
  441. return false;
  442. }
  443. break;
  444. }
  445. }
  446. if ($info['audio']['sample_rate'] > 0) {
  447. $thisfile_mpeg_audio['framelength'] = self::MPEGaudioFrameLength($thisfile_mpeg_audio['bitrate'], $thisfile_mpeg_audio['version'], $thisfile_mpeg_audio['layer'], (int) $thisfile_mpeg_audio['padding'], $info['audio']['sample_rate']);
  448. }
  449. $nextframetestoffset = $offset + 1;
  450. if ($thisfile_mpeg_audio['bitrate'] != 'free') {
  451. $info['audio']['bitrate'] = $thisfile_mpeg_audio['bitrate'];
  452. if (isset($thisfile_mpeg_audio['framelength'])) {
  453. $nextframetestoffset = $offset + $thisfile_mpeg_audio['framelength'];
  454. } else {
  455. $info['error'][] = 'Frame at offset('.$offset.') is has an invalid frame length.';
  456. return false;
  457. }
  458. }
  459. $ExpectedNumberOfAudioBytes = 0;
  460. ////////////////////////////////////////////////////////////////////////////////////
  461. // Variable-bitrate headers
  462. if (substr($headerstring, 4 + 32, 4) == 'VBRI') {
  463. // Fraunhofer VBR header is hardcoded 'VBRI' at offset 0x24 (36)
  464. // specs taken from http://minnie.tuhs.org/pipermail/mp3encoder/2001-January/001800.html
  465. $thisfile_mpeg_audio['bitrate_mode'] = 'vbr';
  466. $thisfile_mpeg_audio['VBR_method'] = 'Fraunhofer';
  467. $info['audio']['codec'] = 'Fraunhofer';
  468. $SideInfoData = substr($headerstring, 4 + 2, 32);
  469. $FraunhoferVBROffset = 36;
  470. $thisfile_mpeg_audio['VBR_encoder_version'] = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 4, 2)); // VbriVersion
  471. $thisfile_mpeg_audio['VBR_encoder_delay'] = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 6, 2)); // VbriDelay
  472. $thisfile_mpeg_audio['VBR_quality'] = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 8, 2)); // VbriQuality
  473. $thisfile_mpeg_audio['VBR_bytes'] = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 10, 4)); // VbriStreamBytes
  474. $thisfile_mpeg_audio['VBR_frames'] = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 14, 4)); // VbriStreamFrames
  475. $thisfile_mpeg_audio['VBR_seek_offsets'] = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 18, 2)); // VbriTableSize
  476. $thisfile_mpeg_audio['VBR_seek_scale'] = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 20, 2)); // VbriTableScale
  477. $thisfile_mpeg_audio['VBR_entry_bytes'] = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 22, 2)); // VbriEntryBytes
  478. $thisfile_mpeg_audio['VBR_entry_frames'] = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 24, 2)); // VbriEntryFrames
  479. $ExpectedNumberOfAudioBytes = $thisfile_mpeg_audio['VBR_bytes'];
  480. $previousbyteoffset = $offset;
  481. for ($i = 0; $i < $thisfile_mpeg_audio['VBR_seek_offsets']; $i++) {
  482. $Fraunhofer_OffsetN = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset, $thisfile_mpeg_audio['VBR_entry_bytes']));
  483. $FraunhoferVBROffset += $thisfile_mpeg_audio['VBR_entry_bytes'];
  484. $thisfile_mpeg_audio['VBR_offsets_relative'][$i] = ($Fraunhofer_OffsetN * $thisfile_mpeg_audio['VBR_seek_scale']);
  485. $thisfile_mpeg_audio['VBR_offsets_absolute'][$i] = ($Fraunhofer_OffsetN * $thisfile_mpeg_audio['VBR_seek_scale']) + $previousbyteoffset;
  486. $previousbyteoffset += $Fraunhofer_OffsetN;
  487. }
  488. } else {
  489. // Xing VBR header is hardcoded 'Xing' at a offset 0x0D (13), 0x15 (21) or 0x24 (36)
  490. // depending on MPEG layer and number of channels
  491. $VBRidOffset = self::XingVBRidOffset($thisfile_mpeg_audio['version'], $thisfile_mpeg_audio['channelmode']);
  492. $SideInfoData = substr($headerstring, 4 + 2, $VBRidOffset - 4);
  493. if ((substr($headerstring, $VBRidOffset, strlen('Xing')) == 'Xing') || (substr($headerstring, $VBRidOffset, strlen('Info')) == 'Info')) {
  494. // 'Xing' is traditional Xing VBR frame
  495. // 'Info' is LAME-encoded CBR (This was done to avoid CBR files to be recognized as traditional Xing VBR files by some decoders.)
  496. // 'Info' *can* legally be used to specify a VBR file as well, however.
  497. // http://www.multiweb.cz/twoinches/MP3inside.htm
  498. //00..03 = "Xing" or "Info"
  499. //04..07 = Flags:
  500. // 0x01 Frames Flag set if value for number of frames in file is stored
  501. // 0x02 Bytes Flag set if value for filesize in bytes is stored
  502. // 0x04 TOC Flag set if values for TOC are stored
  503. // 0x08 VBR Scale Flag set if values for VBR scale is stored
  504. //08..11 Frames: Number of frames in file (including the first Xing/Info one)
  505. //12..15 Bytes: File length in Bytes
  506. //16..115 TOC (Table of Contents):
  507. // Contains of 100 indexes (one Byte length) for easier lookup in file. Approximately solves problem with moving inside file.
  508. // Each Byte has a value according this formula:
  509. // (TOC[i] / 256) * fileLenInBytes
  510. // So if song lasts eg. 240 sec. and you want to jump to 60. sec. (and file is 5 000 000 Bytes length) you can use:
  511. // TOC[(60/240)*100] = TOC[25]
  512. // and corresponding Byte in file is then approximately at:
  513. // (TOC[25]/256) * 5000000
  514. //116..119 VBR Scale
  515. // should be safe to leave this at 'vbr' and let it be overriden to 'cbr' if a CBR preset/mode is used by LAME
  516. // if (substr($headerstring, $VBRidOffset, strlen('Info')) == 'Xing') {
  517. $thisfile_mpeg_audio['bitrate_mode'] = 'vbr';
  518. $thisfile_mpeg_audio['VBR_method'] = 'Xing';
  519. // } else {
  520. // $ScanAsCBR = true;
  521. // $thisfile_mpeg_audio['bitrate_mode'] = 'cbr';
  522. // }
  523. $thisfile_mpeg_audio['xing_flags_raw'] = getid3_lib::BigEndian2Int(substr($headerstring, $VBRidOffset + 4, 4));
  524. $thisfile_mpeg_audio['xing_flags']['frames'] = (bool) ($thisfile_mpeg_audio['xing_flags_raw'] & 0x00000001);
  525. $thisfile_mpeg_audio['xing_flags']['bytes'] = (bool) ($thisfile_mpeg_audio['xing_flags_raw'] & 0x00000002);
  526. $thisfile_mpeg_audio['xing_flags']['toc'] = (bool) ($thisfile_mpeg_audio['xing_flags_raw'] & 0x00000004);
  527. $thisfile_mpeg_audio['xing_flags']['vbr_scale'] = (bool) ($thisfile_mpeg_audio['xing_flags_raw'] & 0x00000008);
  528. if ($thisfile_mpeg_audio['xing_flags']['frames']) {
  529. $thisfile_mpeg_audio['VBR_frames'] = getid3_lib::BigEndian2Int(substr($headerstring, $VBRidOffset + 8, 4));
  530. //$thisfile_mpeg_audio['VBR_frames']--; // don't count header Xing/Info frame
  531. }
  532. if ($thisfile_mpeg_audio['xing_flags']['bytes']) {
  533. $thisfile_mpeg_audio['VBR_bytes'] = getid3_lib::BigEndian2Int(substr($headerstring, $VBRidOffset + 12, 4));
  534. }
  535. //if (($thisfile_mpeg_audio['bitrate'] == 'free') && !empty($thisfile_mpeg_audio['VBR_frames']) && !empty($thisfile_mpeg_audio['VBR_bytes'])) {
  536. //if (!empty($thisfile_mpeg_audio['VBR_frames']) && !empty($thisfile_mpeg_audio['VBR_bytes'])) {
  537. if (!empty($thisfile_mpeg_audio['VBR_frames'])) {
  538. $used_filesize = 0;
  539. if (!empty($thisfile_mpeg_audio['VBR_bytes'])) {
  540. $used_filesize = $thisfile_mpeg_audio['VBR_bytes'];
  541. } elseif (!empty($info['filesize'])) {
  542. $used_filesize = $info['filesize'];
  543. $used_filesize -= intval(@$info['id3v2']['headerlength']);
  544. $used_filesize -= (isset($info['id3v1']) ? 128 : 0);
  545. $used_filesize -= (isset($info['tag_offset_end']) ? $info['tag_offset_end'] - $info['tag_offset_start'] : 0);
  546. $info['warning'][] = 'MP3.Xing header missing VBR_bytes, assuming MPEG audio portion of file is '.number_format($used_filesize).' bytes';
  547. }
  548. $framelengthfloat = $used_filesize / $thisfile_mpeg_audio['VBR_frames'];
  549. if ($thisfile_mpeg_audio['layer'] == '1') {
  550. // BitRate = (((FrameLengthInBytes / 4) - Padding) * SampleRate) / 12
  551. //$info['audio']['bitrate'] = ((($framelengthfloat / 4) - intval($thisfile_mpeg_audio['padding'])) * $thisfile_mpeg_audio['sample_rate']) / 12;
  552. $info['audio']['bitrate'] = ($framelengthfloat / 4) * $thisfile_mpeg_audio['sample_rate'] * (2 / $info['audio']['channels']) / 12;
  553. } else {
  554. // Bitrate = ((FrameLengthInBytes - Padding) * SampleRate) / 144
  555. //$info['audio']['bitrate'] = (($framelengthfloat - intval($thisfile_mpeg_audio['padding'])) * $thisfile_mpeg_audio['sample_rate']) / 144;
  556. $info['audio']['bitrate'] = $framelengthfloat * $thisfile_mpeg_audio['sample_rate'] * (2 / $info['audio']['channels']) / 144;
  557. }
  558. $thisfile_mpeg_audio['framelength'] = floor($framelengthfloat);
  559. }
  560. if ($thisfile_mpeg_audio['xing_flags']['toc']) {
  561. $LAMEtocData = substr($headerstring, $VBRidOffset + 16, 100);
  562. for ($i = 0; $i < 100; $i++) {
  563. $thisfile_mpeg_audio['toc'][$i] = ord($LAMEtocData{$i});
  564. }
  565. }
  566. if ($thisfile_mpeg_audio['xing_flags']['vbr_scale']) {
  567. $thisfile_mpeg_audio['VBR_scale'] = getid3_lib::BigEndian2Int(substr($headerstring, $VBRidOffset + 116, 4));
  568. }
  569. // http://gabriel.mp3-tech.org/mp3infotag.html
  570. if (substr($headerstring, $VBRidOffset + 120, 4) == 'LAME') {
  571. // shortcut
  572. $thisfile_mpeg_audio['LAME'] = array();
  573. $thisfile_mpeg_audio_lame = &$thisfile_mpeg_audio['LAME'];
  574. $thisfile_mpeg_audio_lame['long_version'] = substr($headerstring, $VBRidOffset + 120, 20);
  575. $thisfile_mpeg_audio_lame['short_version'] = substr($thisfile_mpeg_audio_lame['long_version'], 0, 9);
  576. if ($thisfile_mpeg_audio_lame['short_version'] >= 'LAME3.90') {
  577. // extra 11 chars are not part of version string when LAMEtag present
  578. unset($thisfile_mpeg_audio_lame['long_version']);
  579. // It the LAME tag was only introduced in LAME v3.90
  580. // http://www.hydrogenaudio.org/?act=ST&f=15&t=9933
  581. // Offsets of various bytes in http://gabriel.mp3-tech.org/mp3infotag.html
  582. // are assuming a 'Xing' identifier offset of 0x24, which is the case for
  583. // MPEG-1 non-mono, but not for other combinations
  584. $LAMEtagOffsetContant = $VBRidOffset - 0x24;
  585. // shortcuts
  586. $thisfile_mpeg_audio_lame['RGAD'] = array('track'=>array(), 'album'=>array());
  587. $thisfile_mpeg_audio_lame_RGAD = &$thisfile_mpeg_audio_lame['RGAD'];
  588. $thisfile_mpeg_audio_lame_RGAD_track = &$thisfile_mpeg_audio_lame_RGAD['track'];
  589. $thisfile_mpeg_audio_lame_RGAD_album = &$thisfile_mpeg_audio_lame_RGAD['album'];
  590. $thisfile_mpeg_audio_lame['raw'] = array();
  591. $thisfile_mpeg_audio_lame_raw = &$thisfile_mpeg_audio_lame['raw'];
  592. // byte $9B VBR Quality
  593. // This field is there to indicate a quality level, although the scale was not precised in the original Xing specifications.
  594. // Actually overwrites original Xing bytes
  595. unset($thisfile_mpeg_audio['VBR_scale']);
  596. $thisfile_mpeg_audio_lame['vbr_quality'] = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0x9B, 1));
  597. // bytes $9C-$A4 Encoder short VersionString
  598. $thisfile_mpeg_audio_lame['short_version'] = substr($headerstring, $LAMEtagOffsetContant + 0x9C, 9);
  599. // byte $A5 Info Tag revision + VBR method
  600. $LAMEtagRevisionVBRmethod = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xA5, 1));
  601. $thisfile_mpeg_audio_lame['tag_revision'] = ($LAMEtagRevisionVBRmethod & 0xF0) >> 4;
  602. $thisfile_mpeg_audio_lame_raw['vbr_method'] = $LAMEtagRevisionVBRmethod & 0x0F;
  603. $thisfile_mpeg_audio_lame['vbr_method'] = self::LAMEvbrMethodLookup($thisfile_mpeg_audio_lame_raw['vbr_method']);
  604. $thisfile_mpeg_audio['bitrate_mode'] = substr($thisfile_mpeg_audio_lame['vbr_method'], 0, 3); // usually either 'cbr' or 'vbr', but truncates 'vbr-old / vbr-rh' to 'vbr'
  605. // byte $A6 Lowpass filter value
  606. $thisfile_mpeg_audio_lame['lowpass_frequency'] = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xA6, 1)) * 100;
  607. // bytes $A7-$AE Replay Gain
  608. // http://privatewww.essex.ac.uk/~djmrob/replaygain/rg_data_format.html
  609. // bytes $A7-$AA : 32 bit floating point "Peak signal amplitude"
  610. if ($thisfile_mpeg_audio_lame['short_version'] >= 'LAME3.94b') {
  611. // LAME 3.94a16 and later - 9.23 fixed point
  612. // ie 0x0059E2EE / (2^23) = 5890798 / 8388608 = 0.7022378444671630859375
  613. $thisfile_mpeg_audio_lame_RGAD['peak_amplitude'] = (float) ((getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xA7, 4))) / 8388608);
  614. } else {
  615. // LAME 3.94a15 and earlier - 32-bit floating point
  616. // Actually 3.94a16 will fall in here too and be WRONG, but is hard to detect 3.94a16 vs 3.94a15
  617. $thisfile_mpeg_audio_lame_RGAD['peak_amplitude'] = getid3_lib::LittleEndian2Float(substr($headerstring, $LAMEtagOffsetContant + 0xA7, 4));
  618. }
  619. if ($thisfile_mpeg_audio_lame_RGAD['peak_amplitude'] == 0) {
  620. unset($thisfile_mpeg_audio_lame_RGAD['peak_amplitude']);
  621. } else {
  622. $thisfile_mpeg_audio_lame_RGAD['peak_db'] = getid3_lib::RGADamplitude2dB($thisfile_mpeg_audio_lame_RGAD['peak_amplitude']);
  623. }
  624. $thisfile_mpeg_audio_lame_raw['RGAD_track'] = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xAB, 2));
  625. $thisfile_mpeg_audio_lame_raw['RGAD_album'] = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xAD, 2));
  626. if ($thisfile_mpeg_audio_lame_raw['RGAD_track'] != 0) {
  627. $thisfile_mpeg_audio_lame_RGAD_track['raw']['name'] = ($thisfile_mpeg_audio_lame_raw['RGAD_track'] & 0xE000) >> 13;
  628. $thisfile_mpeg_audio_lame_RGAD_track['raw']['originator'] = ($thisfile_mpeg_audio_lame_raw['RGAD_track'] & 0x1C00) >> 10;
  629. $thisfile_mpeg_audio_lame_RGAD_track['raw']['sign_bit'] = ($thisfile_mpeg_audio_lame_raw['RGAD_track'] & 0x0200) >> 9;
  630. $thisfile_mpeg_audio_lame_RGAD_track['raw']['gain_adjust'] = $thisfile_mpeg_audio_lame_raw['RGAD_track'] & 0x01FF;
  631. $thisfile_mpeg_audio_lame_RGAD_track['name'] = getid3_lib::RGADnameLookup($thisfile_mpeg_audio_lame_RGAD_track['raw']['name']);
  632. $thisfile_mpeg_audio_lame_RGAD_track['originator'] = getid3_lib::RGADoriginatorLookup($thisfile_mpeg_audio_lame_RGAD_track['raw']['originator']);
  633. $thisfile_mpeg_audio_lame_RGAD_track['gain_db'] = getid3_lib::RGADadjustmentLookup($thisfile_mpeg_audio_lame_RGAD_track['raw']['gain_adjust'], $thisfile_mpeg_audio_lame_RGAD_track['raw']['sign_bit']);
  634. if (!empty($thisfile_mpeg_audio_lame_RGAD['peak_amplitude'])) {
  635. $info['replay_gain']['track']['peak'] = $thisfile_mpeg_audio_lame_RGAD['peak_amplitude'];
  636. }
  637. $info['replay_gain']['track']['originator'] = $thisfile_mpeg_audio_lame_RGAD_track['originator'];
  638. $info['replay_gain']['track']['adjustment'] = $thisfile_mpeg_audio_lame_RGAD_track['gain_db'];
  639. } else {
  640. unset($thisfile_mpeg_audio_lame_RGAD['track']);
  641. }
  642. if ($thisfile_mpeg_audio_lame_raw['RGAD_album'] != 0) {
  643. $thisfile_mpeg_audio_lame_RGAD_album['raw']['name'] = ($thisfile_mpeg_audio_lame_raw['RGAD_album'] & 0xE000) >> 13;
  644. $thisfile_mpeg_audio_lame_RGAD_album['raw']['originator'] = ($thisfile_mpeg_audio_lame_raw['RGAD_album'] & 0x1C00) >> 10;
  645. $thisfile_mpeg_audio_lame_RGAD_album['raw']['sign_bit'] = ($thisfile_mpeg_audio_lame_raw['RGAD_album'] & 0x0200) >> 9;
  646. $thisfile_mpeg_audio_lame_RGAD_album['raw']['gain_adjust'] = $thisfile_mpeg_audio_lame_raw['RGAD_album'] & 0x01FF;
  647. $thisfile_mpeg_audio_lame_RGAD_album['name'] = getid3_lib::RGADnameLookup($thisfile_mpeg_audio_lame_RGAD_album['raw']['name']);
  648. $thisfile_mpeg_audio_lame_RGAD_album['originator'] = getid3_lib::RGADoriginatorLookup($thisfile_mpeg_audio_lame_RGAD_album['raw']['originator']);
  649. $thisfile_mpeg_audio_lame_RGAD_album['gain_db'] = getid3_lib::RGADadjustmentLookup($thisfile_mpeg_audio_lame_RGAD_album['raw']['gain_adjust'], $thisfile_mpeg_audio_lame_RGAD_album['raw']['sign_bit']);
  650. if (!empty($thisfile_mpeg_audio_lame_RGAD['peak_amplitude'])) {
  651. $info['replay_gain']['album']['peak'] = $thisfile_mpeg_audio_lame_RGAD['peak_amplitude'];
  652. }
  653. $info['replay_gain']['album']['originator'] = $thisfile_mpeg_audio_lame_RGAD_album['originator'];
  654. $info['replay_gain']['album']['adjustment'] = $thisfile_mpeg_audio_lame_RGAD_album['gain_db'];
  655. } else {
  656. unset($thisfile_mpeg_audio_lame_RGAD['album']);
  657. }
  658. if (empty($thisfile_mpeg_audio_lame_RGAD)) {
  659. unset($thisfile_mpeg_audio_lame['RGAD']);
  660. }
  661. // byte $AF Encoding flags + ATH Type
  662. $EncodingFlagsATHtype = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xAF, 1));
  663. $thisfile_mpeg_audio_lame['encoding_flags']['nspsytune'] = (bool) ($EncodingFlagsATHtype & 0x10);
  664. $thisfile_mpeg_audio_lame['encoding_flags']['nssafejoint'] = (bool) ($EncodingFlagsATHtype & 0x20);
  665. $thisfile_mpeg_audio_lame['encoding_flags']['nogap_next'] = (bool) ($EncodingFlagsATHtype & 0x40);
  666. $thisfile_mpeg_audio_lame['encoding_flags']['nogap_prev'] = (bool) ($EncodingFlagsATHtype & 0x80);
  667. $thisfile_mpeg_audio_lame['ath_type'] = $EncodingFlagsATHtype & 0x0F;
  668. // byte $B0 if ABR {specified bitrate} else {minimal bitrate}
  669. $thisfile_mpeg_audio_lame['raw']['abrbitrate_minbitrate'] = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB0, 1));
  670. if ($thisfile_mpeg_audio_lame_raw['vbr_method'] == 2) { // Average BitRate (ABR)
  671. $thisfile_mpeg_audio_lame['bitrate_abr'] = $thisfile_mpeg_audio_lame['raw']['abrbitrate_minbitrate'];
  672. } elseif ($thisfile_mpeg_audio_lame_raw['vbr_method'] == 1) { // Constant BitRate (CBR)
  673. // ignore
  674. } elseif ($thisfile_mpeg_audio_lame['raw']['abrbitrate_minbitrate'] > 0) { // Variable BitRate (VBR) - minimum bitrate
  675. $thisfile_mpeg_audio_lame['bitrate_min'] = $thisfile_mpeg_audio_lame['raw']['abrbitrate_minbitrate'];
  676. }
  677. // bytes $B1-$B3 Encoder delays
  678. $EncoderDelays = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB1, 3));
  679. $thisfile_mpeg_audio_lame['encoder_delay'] = ($EncoderDelays & 0xFFF000) >> 12;
  680. $thisfile_mpeg_audio_lame['end_padding'] = $EncoderDelays & 0x000FFF;
  681. // byte $B4 Misc
  682. $MiscByte = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB4, 1));
  683. $thisfile_mpeg_audio_lame_raw['noise_shaping'] = ($MiscByte & 0x03);
  684. $thisfile_mpeg_audio_lame_raw['stereo_mode'] = ($MiscByte & 0x1C) >> 2;
  685. $thisfile_mpeg_audio_lame_raw['not_optimal_quality'] = ($MiscByte & 0x20) >> 5;
  686. $thisfile_mpeg_audio_lame_raw['source_sample_freq'] = ($MiscByte & 0xC0) >> 6;
  687. $thisfile_mpeg_audio_lame['noise_shaping'] = $thisfile_mpeg_audio_lame_raw['noise_shaping'];
  688. $thisfile_mpeg_audio_lame['stereo_mode'] = self::LAMEmiscStereoModeLookup($thisfile_mpeg_audio_lame_raw['stereo_mode']);
  689. $thisfile_mpeg_audio_lame['not_optimal_quality'] = (bool) $thisfile_mpeg_audio_lame_raw['not_optimal_quality'];
  690. $thisfile_mpeg_audio_lame['source_sample_freq'] = self::LAMEmiscSourceSampleFrequencyLookup($thisfile_mpeg_audio_lame_raw['source_sample_freq']);
  691. // byte $B5 MP3 Gain
  692. $thisfile_mpeg_audio_lame_raw['mp3_gain'] = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB5, 1), false, true);
  693. $thisfile_mpeg_audio_lame['mp3_gain_db'] = (getid3_lib::RGADamplitude2dB(2) / 4) * $thisfile_mpeg_audio_lame_raw['mp3_gain'];
  694. $thisfile_mpeg_audio_lame['mp3_gain_factor'] = pow(2, ($thisfile_mpeg_audio_lame['mp3_gain_db'] / 6));
  695. // bytes $B6-$B7 Preset and surround info
  696. $PresetSurroundBytes = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB6, 2));
  697. // Reserved = ($PresetSurroundBytes & 0xC000);
  698. $thisfile_mpeg_audio_lame_raw['surround_info'] = ($PresetSurroundBytes & 0x3800);
  699. $thisfile_mpeg_audio_lame['surround_info'] = self::LAMEsurroundInfoLookup($thisfile_mpeg_audio_lame_raw['surround_info']);
  700. $thisfile_mpeg_audio_lame['preset_used_id'] = ($PresetSurroundBytes & 0x07FF);
  701. $thisfile_mpeg_audio_lame['preset_used'] = self::LAMEpresetUsedLookup($thisfile_mpeg_audio_lame);
  702. if (!empty($thisfile_mpeg_audio_lame['preset_used_id']) && empty($thisfile_mpeg_audio_lame['preset_used'])) {
  703. $info['warning'][] = 'Unknown LAME preset used ('.$thisfile_mpeg_audio_lame['preset_used_id'].') - please report to info@getid3.org';
  704. }
  705. if (($thisfile_mpeg_audio_lame['short_version'] == 'LAME3.90.') && !empty($thisfile_mpeg_audio_lame['preset_used_id'])) {
  706. // this may change if 3.90.4 ever comes out
  707. $thisfile_mpeg_audio_lame['short_version'] = 'LAME3.90.3';
  708. }
  709. // bytes $B8-$BB MusicLength
  710. $thisfile_mpeg_audio_lame['audio_bytes'] = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB8, 4));
  711. $ExpectedNumberOfAudioBytes = (($thisfile_mpeg_audio_lame['audio_bytes'] > 0) ? $thisfile_mpeg_audio_lame['audio_bytes'] : $thisfile_mpeg_audio['VBR_bytes']);
  712. // bytes $BC-$BD MusicCRC
  713. $thisfile_mpeg_audio_lame['music_crc'] = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xBC, 2));
  714. // bytes $BE-$BF CRC-16 of Info Tag
  715. $thisfile_mpeg_audio_lame['lame_tag_crc'] = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xBE, 2));
  716. // LAME CBR
  717. if ($thisfile_mpeg_audio_lame_raw['vbr_method'] == 1) {
  718. $thisfile_mpeg_audio['bitrate_mode'] = 'cbr';
  719. $thisfile_mpeg_audio['bitrate'] = self::ClosestStandardMP3Bitrate($thisfile_mpeg_audio['bitrate']);
  720. $info['audio']['bitrate'] = $thisfile_mpeg_audio['bitrate'];
  721. //if (empty($thisfile_mpeg_audio['bitrate']) || (!empty($thisfile_mpeg_audio_lame['bitrate_min']) && ($thisfile_mpeg_audio_lame['bitrate_min'] != 255))) {
  722. // $thisfile_mpeg_audio['bitrate'] = $thisfile_mpeg_audio_lame['bitrate_min'];
  723. //}
  724. }
  725. }
  726. }
  727. } else {
  728. // not Fraunhofer or Xing VBR methods, most likely CBR (but could be VBR with no header)
  729. $thisfile_mpeg_audio['bitrate_mode'] = 'cbr';
  730. if ($recursivesearch) {
  731. $thisfile_mpeg_audio['bitrate_mode'] = 'vbr';
  732. if ($this->RecursiveFrameScanning($offset, $nextframetestoffset, true)) {
  733. $recursivesearch = false;
  734. $thisfile_mpeg_audio['bitrate_mode'] = 'cbr';
  735. }
  736. if ($thisfile_mpeg_audio['bitrate_mode'] == 'vbr') {
  737. $info['warning'][] = 'VBR file with no VBR header. Bitrate values calculated from actual frame bitrates.';
  738. }
  739. }
  740. }
  741. }
  742. if (($ExpectedNumberOfAudioBytes > 0) && ($ExpectedNumberOfAudioBytes != ($info['avdataend'] - $info['avdataoffset']))) {
  743. if ($ExpectedNumberOfAudioBytes > ($info['avdataend'] - $info['avdataoffset'])) {
  744. if ($this->isDependencyFor('matroska') || $this->isDependencyFor('riff')) {
  745. // ignore, audio data is broken into chunks so will always be data "missing"
  746. }
  747. elseif (($ExpectedNumberOfAudioBytes - ($info['avdataend'] - $info['avdataoffset'])) == 1) {
  748. $this->warning('Last byte of data truncated (this is a known bug in Meracl ID3 Tag Writer before v1.3.5)');
  749. }
  750. else {
  751. $this->warning('Probable truncated file: expecting '.$ExpectedNumberOfAudioBytes.' bytes of audio data, only found '.($info['avdataend'] - $info['avdataoffset']).' (short by '.($ExpectedNumberOfAudioBytes - ($info['avdataend'] - $info['avdataoffset'])).' bytes)');
  752. }
  753. } else {
  754. if ((($info['avdataend'] - $info['avdataoffset']) - $ExpectedNumberOfAudioBytes) == 1) {
  755. // $prenullbytefileoffset = $this->ftell();
  756. // $this->fseek($info['avdataend']);
  757. // $PossibleNullByte = $this->fread(1);
  758. // $this->fseek($prenullbytefileoffset);
  759. // if ($PossibleNullByte === "\x00") {
  760. $info['avdataend']--;
  761. // $info['warning'][] = 'Extra null byte at end of MP3 data assumed to be RIFF padding and therefore ignored';
  762. // } else {
  763. // $info['warning'][] = 'Too much data in file: expecting '.$ExpectedNumberOfAudioBytes.' bytes of audio data, found '.($info['avdataend'] - $info['avdataoffset']).' ('.(($info['avdataend'] - $info['avdataoffset']) - $ExpectedNumberOfAudioBytes).' bytes too many)';
  764. // }
  765. } else {
  766. $info['warning'][] = 'Too much data in file: expecting '.$ExpectedNumberOfAudioBytes.' bytes of audio data, found '.($info['avdataend'] - $info['avdataoffset']).' ('.(($info['avdataend'] - $info['avdataoffset']) - $ExpectedNumberOfAudioBytes).' bytes too many)';
  767. }
  768. }
  769. }
  770. if (($thisfile_mpeg_audio['bitrate'] == 'free') && empty($info['audio']['bitrate'])) {
  771. if (($offset == $info['avdataoffset']) && empty($thisfile_mpeg_audio['VBR_frames'])) {
  772. $framebytelength = $this->FreeFormatFrameLength($offset, true);
  773. if ($framebytelength > 0) {
  774. $thisfile_mpeg_audio['framelength'] = $framebytelength;
  775. if ($thisfile_mpeg_audio['layer'] == '1') {
  776. // BitRate = (((FrameLengthInBytes / 4) - Padding) * SampleRate) / 12
  777. $info['audio']['bitrate'] = ((($framebytelength / 4) - intval($thisfile_mpeg_audio['padding'])) * $thisfile_mpeg_audio['sample_rate']) / 12;
  778. } else {
  779. // Bitrate = ((FrameLengthInBytes - Padding) * SampleRate) / 144
  780. $info['audio']['bitrate'] = (($framebytelength - intval($thisfile_mpeg_audio['padding'])) * $thisfile_mpeg_audio['sample_rate']) / 144;
  781. }
  782. } else {
  783. $info['error'][] = 'Error calculating frame length of free-format MP3 without Xing/LAME header';
  784. }
  785. }
  786. }
  787. if (isset($thisfile_mpeg_audio['VBR_frames']) ? $thisfile_mpeg_audio['VBR_frames'] : '') {
  788. switch ($thisfile_mpeg_audio['bitrate_mode']) {
  789. case 'vbr':
  790. case 'abr':
  791. $bytes_per_frame = 1152;
  792. if (($thisfile_mpeg_audio['version'] == '1') && ($thisfile_mpeg_audio['layer'] == 1)) {
  793. $bytes_per_frame = 384;
  794. } elseif ((($thisfile_mpeg_audio['version'] == '2') || ($thisfile_mpeg_audio['version'] == '2.5')) && ($thisfile_mpeg_audio['layer'] == 3)) {
  795. $bytes_per_frame = 576;
  796. }
  797. $thisfile_mpeg_audio['VBR_bitrate'] = (isset($thisfile_mpeg_audio['VBR_bytes']) ? (($thisfile_mpeg_audio['VBR_bytes'] / $thisfile_mpeg_audio['VBR_frames']) * 8) * ($info['audio']['sample_rate'] / $bytes_per_frame) : 0);
  798. if ($thisfile_mpeg_audio['VBR_bitrate'] > 0) {
  799. $info['audio']['bitrate'] = $thisfile_mpeg_audio['VBR_bitrate'];
  800. $thisfile_mpeg_audio['bitrate'] = $thisfile_mpeg_audio['VBR_bitrate']; // to avoid confusion
  801. }
  802. break;
  803. }
  804. }
  805. // End variable-bitrate headers
  806. ////////////////////////////////////////////////////////////////////////////////////
  807. if ($recursivesearch) {
  808. if (!$this->RecursiveFrameScanning($offset, $nextframetestoffset, $ScanAsCBR)) {
  809. return false;
  810. }
  811. }
  812. //if (false) {
  813. // // experimental side info parsing section - not returning anything useful yet
  814. //
  815. // $SideInfoBitstream = getid3_lib::BigEndian2Bin($SideInfoData);
  816. // $SideInfoOffset = 0;
  817. //
  818. // if ($thisfile_mpeg_audio['version'] == '1') {
  819. // if ($thisfile_mpeg_audio['channelmode'] == 'mono') {
  820. // // MPEG-1 (mono)
  821. // $thisfile_mpeg_audio['side_info']['main_data_begin'] = substr($SideInfoBitstream, $SideInfoOffset, 9);
  822. // $SideInfoOffset += 9;
  823. // $SideInfoOffset += 5;
  824. // } else {
  825. // // MPEG-1 (stereo, joint-stereo, dual-channel)
  826. // $thisfile_mpeg_audio['side_info']['main_data_begin'] = substr($SideInfoBitstream, $SideInfoOffset, 9);
  827. // $SideInfoOffset += 9;
  828. // $SideInfoOffset += 3;
  829. // }
  830. // } else { // 2 or 2.5
  831. // if ($thisfile_mpeg_audio['channelmode'] == 'mono') {
  832. // // MPEG-2, MPEG-2.5 (mono)
  833. // $thisfile_mpeg_audio['side_info']['main_data_begin'] = substr($SideInfoBitstream, $SideInfoOffset, 8);
  834. // $SideInfoOffset += 8;
  835. // $SideInfoOffset += 1;
  836. // } else {
  837. // // MPEG-2, MPEG-2.5 (stereo, joint-stereo, dual-channel)
  838. // $thisfile_mpeg_audio['side_info']['main_data_begin'] = substr($SideInfoBitstream, $SideInfoOffset, 8);
  839. // $SideInfoOffset += 8;
  840. // $SideInfoOffset += 2;
  841. // }
  842. // }
  843. //
  844. // if ($thisfile_mpeg_audio['version'] == '1') {
  845. // for ($channel = 0; $channel < $info['audio']['channels']; $channel++) {
  846. // for ($scfsi_band = 0; $scfsi_band < 4; $scfsi_band++) {
  847. // $thisfile_mpeg_audio['scfsi'][$channel][$scfsi_band] = substr($SideInfoBitstream, $SideInfoOffset, 1);
  848. // $SideInfoOffset += 2;
  849. // }
  850. // }
  851. // }
  852. // for ($granule = 0; $granule < (($thisfile_mpeg_audio['version'] == '1') ? 2 : 1); $granule++) {
  853. // for ($channel = 0; $channel < $info['audio']['channels']; $channel++) {
  854. // $thisfile_mpeg_audio['part2_3_length'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 12);
  855. // $SideInfoOffset += 12;
  856. // $thisfile_mpeg_audio['big_values'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 9);
  857. // $SideInfoOffset += 9;
  858. // $thisfile_mpeg_audio['global_gain'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 8);
  859. // $SideInfoOffset += 8;
  860. // if ($thisfile_mpeg_audio['version'] == '1') {
  861. // $thisfile_mpeg_audio['scalefac_compress'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 4);
  862. // $SideInfoOffset += 4;
  863. // } else {
  864. // $thisfile_mpeg_audio['scalefac_compress'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 9);
  865. // $SideInfoOffset += 9;
  866. // }
  867. // $thisfile_mpeg_audio['window_switching_flag'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 1);
  868. // $SideInfoOffset += 1;
  869. //
  870. // if ($thisfile_mpeg_audio['window_switching_flag'][$granule][$channel] == '1') {
  871. //
  872. // $thisfile_mpeg_audio['block_type'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 2);
  873. // $SideInfoOffset += 2;
  874. // $thisfile_mpeg_audio['mixed_block_flag'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 1);
  875. // $SideInfoOffset += 1;
  876. //
  877. // for ($region = 0; $region < 2; $region++) {
  878. // $thisfile_mpeg_audio['table_select'][$granule][$channel][$region] = substr($SideInfoBitstream, $SideInfoOffset, 5);
  879. // $SideInfoOffset += 5;
  880. // }
  881. // $thisfile_mpeg_audio['table_select'][$granule][$channel][2] = 0;
  882. //
  883. // for ($window = 0; $window < 3; $window++) {
  884. // $thisfile_mpeg_audio['subblock_gain'][$granule][$channel][$window] = substr($SideInfoBitstream, $SideInfoOffset, 3);
  885. // $SideInfoOffset += 3;
  886. // }
  887. //
  888. // } else {
  889. //
  890. // for ($region = 0; $region < 3; $region++) {
  891. // $thisfile_mpeg_audio['table_select'][$granule][$channel][$region] = substr($SideInfoBitstream, $SideInfoOffset, 5);
  892. // $SideInfoOffset += 5;
  893. // }
  894. //
  895. // $thisfile_mpeg_audio['region0_count'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 4);
  896. // $SideInfoOffset += 4;
  897. // $thisfile_mpeg_audio['region1_count'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 3);
  898. // $SideInfoOffset += 3;
  899. // $thisfile_mpeg_audio['block_type'][$granule][$channel] = 0;
  900. // }
  901. //
  902. // if ($thisfile_mpeg_audio['version'] == '1') {
  903. // $thisfile_mpeg_audio['preflag'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 1);
  904. // $SideInfoOffset += 1;
  905. // }
  906. // $thisfile_mpeg_audio['scalefac_scale'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 1);
  907. // $SideInfoOffset += 1;
  908. // $thisfile_mpeg_audio['count1table_select'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 1);
  909. // $SideInfoOffset += 1;
  910. // }
  911. // }
  912. //}
  913. return true;
  914. }
  915. public function RecursiveFrameScanning(&$offset, &$nextframetestoffset, $ScanAsCBR) {
  916. $info = &$this->getid3->info;
  917. $firstframetestarray = array('error'=>'', 'warning'=>'', 'avdataend'=>$info['avdataend'], 'avdataoffset'=>$info['avdataoffset']);
  918. $this->decodeMPEGaudioHeader($offset, $firstframetestarray, false);
  919. for ($i = 0; $i < GETID3_MP3_VALID_CHECK_FRAMES; $i++) {
  920. // check next GETID3_MP3_VALID_CHECK_FRAMES frames for validity, to make sure we haven't run across a false synch
  921. if (($nextframetestoffset + 4) >= $info['avdataend']) {
  922. // end of file
  923. return true;
  924. }
  925. $nextframetestarray = array('error'=>'', 'warning'=>'', 'avdataend'=>$info['avdataend'], 'avdataoffset'=>$info['avdataoffset']);
  926. if ($this->decodeMPEGaudioHeader($nextframetestoffset, $nextframetestarray, false)) {
  927. if ($ScanAsCBR) {
  928. // force CBR mode, used for trying to pick out invalid audio streams with valid(?) VBR headers, or VBR streams with no VBR header
  929. if (!isset($nextframetestarray['mpeg']['audio']['bitrate']) || !isset($firstframetestarray['mpeg']['audio']['bitrate']) || ($nextframetestarray['mpeg']['audio']['bitrate'] != $firstframetestarray['mpeg']['audio']['bitrate'])) {
  930. return false;
  931. }
  932. }
  933. // next frame is OK, get ready to check the one after that
  934. if (isset($nextframetestarray['mpeg']['audio']['framelength']) && ($nextframetestarray['mpeg']['audio']['framelength'] > 0)) {
  935. $nextframetestoffset += $nextframetestarray['mpeg']['audio']['framelength'];
  936. } else {
  937. $info['error'][] = 'Frame at offset ('.$offset.') is has an invalid frame length.';
  938. return false;
  939. }
  940. } elseif (!empty($firstframetestarray['mpeg']['audio']['framelength']) && (($nextframetestoffset + $firstframetestarray['mpeg']['audio']['framelength']) > $info['avdataend'])) {
  941. // it's not the end of the file, but there's not enough data left for another frame, so assume it's garbage/padding and return OK
  942. return true;
  943. } else {
  944. // next frame is not valid, note the error and fail, so scanning can contiue for a valid frame sequence
  945. $info['warning'][] = 'Frame at offset ('.$offset.') is valid, but the next one at ('.$nextframetestoffset.') is not.';
  946. return false;
  947. }
  948. }
  949. return true;
  950. }
  951. public function FreeFormatFrameLength($offset, $deepscan=false) {
  952. $info = &$this->getid3->info;
  953. $this->fseek($offset);
  954. $MPEGaudioData = $this->fread(32768);
  955. $SyncPattern1 = substr($MPEGaudioData, 0, 4);
  956. // may be different pattern due to padding
  957. $SyncPattern2 = $SyncPattern1{0}.$SyncPattern1{1}.chr(ord($SyncPattern1{2}) | 0x02).$SyncPattern1{3};
  958. if ($SyncPattern2 === $SyncPattern1) {
  959. $SyncPattern2 = $SyncPattern1{0}.$SyncPattern1{1}.chr(ord($SyncPattern1{2}) & 0xFD).$SyncPattern1{3};
  960. }
  961. $framelength = false;
  962. $framelength1 = strpos($MPEGaudioData, $SyncPattern1, 4);
  963. $framelength2 = strpos($MPEGaudioData, $SyncPattern2, 4);
  964. if ($framelength1 > 4) {
  965. $framelength = $framelength1;
  966. }
  967. if (($framelength2 > 4) && ($framelength2 < $framelength1)) {
  968. $framelength = $framelength2;
  969. }
  970. if (!$framelength) {
  971. // LAME 3.88 has a different value for modeextension on the first frame vs the rest
  972. $framelength1 = strpos($MPEGaudioData, substr($SyncPattern1, 0, 3), 4);
  973. $framelength2 = strpos($MPEGaudioData, substr($SyncPattern2, 0, 3), 4);
  974. if ($framelength1 > 4) {
  975. $framelength = $framelength1;
  976. }
  977. if (($framelength2 > 4) && ($framelength2 < $framelength1)) {
  978. $framelength = $framelength2;
  979. }
  980. if (!$framelength) {
  981. $info['error'][] = 'Cannot find next free-format synch pattern ('.getid3_lib::PrintHexBytes($SyncPattern1).' or '.getid3_lib::PrintHexBytes($SyncPattern2).') after offset '.$offset;
  982. return false;
  983. } else {
  984. $info['warning'][] = 'ModeExtension varies between first frame and other frames (known free-format issue in LAME 3.88)';
  985. $info['audio']['codec'] = 'LAME';
  986. $info['audio']['encoder'] = 'LAME3.88';
  987. $SyncPattern1 = substr($SyncPattern1, 0, 3);
  988. $SyncPattern2 = substr($SyncPattern2, 0, 3);
  989. }
  990. }
  991. if ($deepscan) {
  992. $ActualFrameLengthValues = array();
  993. $nextoffset = $offset + $framelength;
  994. while ($nextoffset < ($info['avdataend'] - 6)) {
  995. $this->fseek($nextoffset - 1);
  996. $NextSyncPattern = $this->fread(6);
  997. if ((substr($NextSyncPattern, 1, strlen($SyncPattern1)) == $SyncPattern1) || (substr($NextSyncPattern, 1, strlen($SyncPattern2)) == $SyncPattern2)) {
  998. // good - found where expected
  999. $ActualFrameLengthValues[] = $framelength;
  1000. } elseif ((substr($NextSyncPattern, 0, strlen($SyncPattern1)) == $SyncPattern1) || (substr($NextSyncPattern, 0, strlen($SyncPattern2)) == $SyncPattern2)) {
  1001. // ok - found one byte earlier than expected (last frame wasn't padded, first frame was)
  1002. $ActualFrameLengthValues[] = ($framelength - 1);
  1003. $nextoffset--;
  1004. } elseif ((substr($NextSyncPattern, 2, strlen($SyncPattern1)) == $SyncPattern1) || (substr($NextSyncPattern, 2, strlen($SyncPattern2)) == $SyncPattern2)) {
  1005. // ok - found one byte later than expected (last frame was padded, first frame wasn't)
  1006. $ActualFrameLengthValues[] = ($framelength + 1);
  1007. $nextoffset++;
  1008. } else {
  1009. $info['error'][] = 'Did not find expected free-format sync pattern at offset '.$nextoffset;
  1010. return false;
  1011. }
  1012. $nextoffset += $framelength;
  1013. }
  1014. if (count($ActualFrameLengthValues) > 0) {
  1015. $framelength = intval(round(array_sum($ActualFrameLengthValues) / count($ActualFrameLengthValues)));
  1016. }
  1017. }
  1018. return $framelength;
  1019. }
  1020. public function getOnlyMPEGaudioInfoBruteForce() {
  1021. $MPEGaudioHeaderDecodeCache = array();
  1022. $MPEGaudioHeaderValidCache = array();
  1023. $MPEGaudioHeaderLengthCache = array();
  1024. $MPEGaudioVersionLookup = self::MPEGaudioVersionArray();
  1025. $MPEGaudioLayerLookup = self::MPEGaudioLayerArray();
  1026. $MPEGaudioBitrateLookup = self::MPEGaudioBitrateArray();
  1027. $MPEGaudioFrequencyLookup = self::MPEGaudioFrequencyArray();
  1028. $MPEGaudioChannelModeLookup = self::MPEGaudioChannelModeArray();
  1029. $MPEGaudioModeExtensionLookup = self::MPEGaudioModeExtensionArray();
  1030. $MPEGaudioEmphasisLookup = self::MPEGaudioEmphasisArray();
  1031. $LongMPEGversionLookup = array();
  1032. $LongMPEGlayerLookup = array();
  1033. $LongMPEGbitrateLookup = array();
  1034. $LongMPEGpaddingLookup = array();
  1035. $LongMPEGfrequencyLookup = array();
  1036. $Distribution['bitrate'] = array();
  1037. $Distribution['frequency'] = array();
  1038. $Distribution['layer'] = array();
  1039. $Distribution['version'] = array();
  1040. $Distribution['padding'] = array();
  1041. $info = &$this->getid3->info;
  1042. $this->fseek($info['avdataoffset']);
  1043. $max_frames_scan = 5000;
  1044. $frames_scanned = 0;
  1045. $previousvalidframe = $info['avdataoffset'];
  1046. while ($this->ftell() < $info['avdataend']) {
  1047. set_time_limit(30);
  1048. $head4 = $this->fread(4);
  1049. if (strlen($head4) < 4) {
  1050. break;
  1051. }
  1052. if ($head4{0} != "\xFF") {
  1053. for ($i = 1; $i < 4; $i++) {
  1054. if ($head4{$i} == "\xFF") {
  1055. $this->fseek($i - 4, SEEK_CUR);
  1056. continue 2;
  1057. }
  1058. }
  1059. continue;
  1060. }
  1061. if (!isset($MPEGaudioHeaderDecodeCache[$head4])) {
  1062. $MPEGaudioHeaderDecodeCache[$head4] = self::MPEGaudioHeaderDecode($head4);
  1063. }
  1064. if (!isset($MPEGaudioHeaderValidCache[$head4])) {
  1065. $MPEGaudioHeaderValidCache[$head4] = self::MPEGaudioHeaderValid($MPEGaudioHeaderDecodeCache[$head4], false, false);
  1066. }
  1067. if ($MPEGaudioHeaderValidCache[$head4]) {
  1068. if (!isset($MPEGaudioHeaderLengthCache[$head4])) {
  1069. $LongMPEGversionLookup[$head4] = $MPEGaudioVersionLookup[$MPEGaudioHeaderDecodeCache[$head4]['version']];
  1070. $LongMPEGlayerLookup[$head4] = $MPEGaudioLayerLookup[$MPEGaudioHeaderDecodeCache[$head4]['layer']];
  1071. $LongMPEGbitrateLookup[$head4] = $MPEGaudioBitrateLookup[$LongMPEGversionLookup[$head4]][$LongMPEGlayerLookup[$head4]][$MPEGaudioHeaderDecodeCache[$head4]['bitrate']];
  1072. $LongMPEGpaddingLookup[$head4] = (bool) $MPEGaudioHeaderDecodeCache[$head4]['padding'];
  1073. $LongMPEGfrequencyLookup[$head4] = $MPEGaudioFrequencyLookup[$LongMPEGversionLookup[$head4]][$MPEGaudioHeaderDecodeCache[$head4]['sample_rate']];
  1074. $MPEGaudioHeaderLengthCache[$head4] = self::MPEGaudioFrameLength(
  1075. $LongMPEGbitrateLookup[$head4],
  1076. $LongMPEGversionLookup[$head4],
  1077. $LongMPEGlayerLookup[$head4],
  1078. $LongMPEGpaddingLookup[$head4],
  1079. $LongMPEGfrequencyLookup[$head4]);
  1080. }
  1081. if ($MPEGaudioHeaderLengthCache[$head4] > 4) {
  1082. $WhereWeWere = $this->ftell();
  1083. $this->fseek($MPEGaudioHeaderLengthCache[$head4] - 4, SEEK_CUR);
  1084. $next4 = $this->fread(4);
  1085. if ($next4{0} == "\xFF") {
  1086. if (!isset($MPEGaudioHeaderDecodeCache[$next4])) {
  1087. $MPEGaudioHeaderDecodeCache[$next4] = self::MPEGaudioHeaderDecode($next4);
  1088. }
  1089. if (!isset($MPEGaudioHeaderValidCache[$next4])) {
  1090. $MPEGaudioHeaderValidCache[$next4] = self::MPEGaudioHeaderValid($MPEGaudioHeaderDecodeCache[$next4], false, false);
  1091. }
  1092. if ($MPEGaudioHeaderValidCache[$next4]) {
  1093. $this->fseek(-4, SEEK_CUR);
  1094. getid3_lib::safe_inc($Distribution['bitrate'][$LongMPEGbitrateLookup[$head4]]);
  1095. getid3_lib::safe_inc($Distribution['layer'][$LongMPEGlayerLookup[$head4]]);
  1096. getid3_lib::safe_inc($Distribution['version'][$LongMPEGversionLookup[$head4]]);
  1097. getid3_lib::safe_inc($Distribution['padding'][intval($LongMPEGpaddingLookup[$head4])]);
  1098. getid3_lib::safe_inc($Distribution['frequency'][$LongMPEGfrequencyLookup[$head4]]);
  1099. if ($max_frames_scan && (++$frames_scanned >= $max_frames_scan)) {
  1100. $pct_data_scanned = ($this->ftell() - $info['avdataoffset']) / ($info['avdataend'] - $info['avdataoffset']);
  1101. $info['warning'][] = 'too many MPEG audio frames to scan, only scanned first '.$max_frames_scan.' frames ('.number_format($pct_data_scanned * 100, 1).'% of file) and extrapolated distribution, playtime and bitrate may be incorrect.';
  1102. foreach ($Distribution as $key1 => $value1) {
  1103. foreach ($value1 as $key2 => $value2) {
  1104. $Distribution[$key1][$key2] = round($value2 / $pct_data_scanned);
  1105. }
  1106. }
  1107. break;
  1108. }
  1109. continue;
  1110. }
  1111. }
  1112. unset($next4);
  1113. $this->fseek($WhereWeWere - 3);
  1114. }
  1115. }
  1116. }
  1117. foreach ($Distribution as $key => $value) {
  1118. ksort($Distribution[$key], SORT_NUMERIC);
  1119. }
  1120. ksort($Distribution['version'], SORT_STRING);
  1121. $info['mpeg']['audio']['bitrate_distribution'] = $Distribution['bitrate'];
  1122. $info['mpeg']['audio']['frequency_distribution'] = $Distribution['frequency'];
  1123. $info['mpeg']['audio']['layer_distribution'] = $Distribution['layer'];
  1124. $info['mpeg']['audio']['version_distribution'] = $Distribution['version'];
  1125. $info['mpeg']['audio']['padding_distribution'] = $Distribution['padding'];
  1126. if (count($Distribution['version']) > 1) {
  1127. $info['error'][] = 'Corrupt file - more than one MPEG version detected';
  1128. }
  1129. if (count($Distribution['layer']) > 1) {
  1130. $info['error'][] = 'Corrupt file - more than one MPEG layer detected';
  1131. }
  1132. if (count($Distribution['frequency']) > 1) {
  1133. $info['error'][] = 'Corrupt file - more than one MPEG sample rate detected';
  1134. }
  1135. $bittotal = 0;
  1136. foreach ($Distribution['bitrate'] as $bitratevalue => $bitratecount) {
  1137. if ($bitratevalue != 'free') {
  1138. $bittotal += ($bitratevalue * $bitratecount);
  1139. }
  1140. }
  1141. $info['mpeg']['audio']['frame_count'] = array_sum($Distribution['bitrate']);
  1142. if ($info['mpeg']['audio']['frame_count'] == 0) {
  1143. $info['error'][] = 'no MPEG audio frames found';
  1144. return false;
  1145. }
  1146. $info['mpeg']['audio']['bitrate'] = ($bittotal / $info['mpeg']['audio']['frame_count']);
  1147. $info['mpeg']['audio']['bitrate_mode'] = ((count($Distribution['bitrate']) > 0) ? 'vbr' : 'cbr');
  1148. $info['mpeg']['audio']['sample_rate'] = getid3_lib::array_max($Distribution['frequency'], true);
  1149. $info['audio']['bitrate'] = $info['mpeg']['audio']['bitrate'];
  1150. $info['audio']['bitrate_mode'] = $info['mpeg']['audio']['bitrate_mode'];
  1151. $info['audio']['sample_rate'] = $info['mpeg']['audio']['sample_rate'];
  1152. $info['audio']['dataformat'] = 'mp'.getid3_lib::array_max($Distribution['layer'], true);
  1153. $info['fileformat'] = $info['audio']['dataformat'];
  1154. return true;
  1155. }
  1156. public function getOnlyMPEGaudioInfo($avdataoffset, $BitrateHistogram=false) {
  1157. // looks for synch, decodes MPEG audio header
  1158. $info = &$this->getid3->info;
  1159. static $MPEGaudioVersionLookup;
  1160. static $MPEGaudioLayerLookup;
  1161. static $MPEGaudioBitrateLookup;
  1162. if (empty($MPEGaudioVersionLookup)) {
  1163. $MPEGaudioVersionLookup = self::MPEGaudioVersionArray();
  1164. $MPEGaudioLayerLookup = self::MPEGaudioLayerArray();
  1165. $MPEGaudioBitrateLookup = self::MPEGaudioBitrateArray();
  1166. }
  1167. $this->fseek($avdataoffset);
  1168. $sync_seek_buffer_size = min(128 * 1024, $info['avdataend'] - $avdataoffset);
  1169. if ($sync_seek_buffer_size <= 0) {
  1170. $info['error'][] = 'Invalid $sync_seek_buffer_size at offset '.$avdataoffset;
  1171. return false;
  1172. }
  1173. $header = $this->fread($sync_seek_buffer_size);
  1174. $sync_seek_buffer_size = strlen($header);
  1175. $SynchSeekOffset = 0;
  1176. while ($SynchSeekOffset < $sync_seek_buffer_size) {
  1177. if ((($avdataoffset + $SynchSeekOffset) < $info['avdataend']) && !feof($this->getid3->fp)) {
  1178. if ($SynchSeekOffset > $sync_seek_buffer_size) {
  1179. // if a synch's not found within the first 128k bytes, then give up
  1180. $info['error'][] = 'Could not find valid MPEG audio synch within the first '.round($sync_seek_buffer_size / 1024).'kB';
  1181. if (isset($info['audio']['bitrate'])) {
  1182. unset($info['audio']['bitrate']);
  1183. }
  1184. if (isset($info['mpeg']['audio'])) {
  1185. unset($info['mpeg']['audio']);
  1186. }
  1187. if (empty($info['mpeg'])) {
  1188. unset($info['mpeg']);
  1189. }
  1190. return false;
  1191. } elseif (feof($this->getid3->fp)) {
  1192. $info['error'][] = 'Could not find valid MPEG audio synch before end of file';
  1193. if (isset($info['audio']['bitrate'])) {
  1194. unset($info['audio']['bitrate']);
  1195. }
  1196. if (isset($info['mpeg']['audio'])) {
  1197. unset($info['mpeg']['audio']);
  1198. }
  1199. if (isset($info['mpeg']) && (!is_array($info['mpeg']) || (count($info['mpeg']) == 0))) {
  1200. unset($info['mpeg']);
  1201. }
  1202. return false;
  1203. }
  1204. }
  1205. if (($SynchSeekOffset + 1) >= strlen($header)) {
  1206. $info['error'][] = 'Could not find valid MPEG synch before end of file';
  1207. return false;
  1208. }
  1209. if (($header{$SynchSeekOffset} == "\xFF") && ($header{($SynchSeekOffset + 1)} > "\xE0")) { // synch detected
  1210. if (!isset($FirstFrameThisfileInfo) && !isset($info['mpeg']['audio'])) {
  1211. $FirstFrameThisfileInfo = $info;
  1212. $FirstFrameAVDataOffset = $avdataoffset + $SynchSeekOffset;
  1213. if (!$this->decodeMPEGaudioHeader($FirstFrameAVDataOffset, $FirstFrameThisfileInfo, false)) {
  1214. // if this is the first valid MPEG-audio frame, save it in case it's a VBR header frame and there's
  1215. // garbage between this frame and a valid sequence of MPEG-audio frames, to be restored below
  1216. unset($FirstFrameThisfileInfo);
  1217. }
  1218. }
  1219. $dummy = $info; // only overwrite real data if valid header found
  1220. if ($this->decodeMPEGaudioHeader($avdataoffset + $SynchSeekOffset, $dummy, true)) {
  1221. $info = $dummy;
  1222. $info['avdataoffset'] = $avdataoffset + $SynchSeekOffset;
  1223. switch (isset($info['fileformat']) ? $info['fileformat'] : '') {
  1224. case '':
  1225. case 'id3':
  1226. case 'ape':
  1227. case 'mp3':
  1228. $info['fileformat'] = 'mp3';
  1229. $info['audio']['dataformat'] = 'mp3';
  1230. break;
  1231. }
  1232. if (isset($FirstFrameThisfileInfo['mpeg']['audio']['bitrate_mode']) && ($FirstFrameThisfileInfo['mpeg']['audio']['bitrate_mode'] == 'vbr')) {
  1233. if (!(abs($info['audio']['bitrate'] - $FirstFrameThisfileInfo['audio']['bitrate']) <= 1)) {
  1234. // If there is garbage data between a valid VBR header frame and a sequence
  1235. // of valid MPEG-audio frames the VBR data is no longer discarded.
  1236. $info = $FirstFrameThisfileInfo;
  1237. $info['avdataoffset'] = $FirstFrameAVDataOffset;
  1238. $info['fileformat'] = 'mp3';
  1239. $info['audio']['dataformat'] = 'mp3';
  1240. $dummy = $info;
  1241. unset($dummy['mpeg']['audio']);
  1242. $GarbageOffsetStart = $FirstFrameAVDataOffset + $FirstFrameThisfileInfo['mpeg']['audio']['framelength'];
  1243. $GarbageOffsetEnd = $avdataoffset + $SynchSeekOffset;
  1244. if ($this->decodeMPEGaudioHeader($GarbageOffsetEnd, $dummy, true, true)) {
  1245. $info = $dummy;
  1246. $info['avdataoffset'] = $GarbageOffsetEnd;
  1247. $info['warning'][] = 'apparently-valid VBR header not used because could not find '.GETID3_MP3_VALID_CHECK_FRAMES.' consecutive MPEG-audio frames immediately after VBR header (garbage data for '.($GarbageOffsetEnd - $GarbageOffsetStart).' bytes between '.$GarbageOffsetStart.' and '.$GarbageOffsetEnd.'), but did find valid CBR stream starting at '.$GarbageOffsetEnd;
  1248. } else {
  1249. $info['warning'][] = 'using data from VBR header even though could not find '.GETID3_MP3_VALID_CHECK_FRAMES.' consecutive MPEG-audio frames immediately after VBR header (garbage data for '.($GarbageOffsetEnd - $GarbageOffsetStart).' bytes between '.$GarbageOffsetStart.' and '.$GarbageOffsetEnd.')';
  1250. }
  1251. }
  1252. }
  1253. if (isset($info['mpeg']['audio']['bitrate_mode']) && ($info['mpeg']['audio']['bitrate_mode'] == 'vbr') && !isset($info['mpeg']['audio']['VBR_method'])) {
  1254. // VBR file with no VBR header
  1255. $BitrateHistogram = true;
  1256. }
  1257. if ($BitrateHistogram) {
  1258. $info['mpeg']['audio']['stereo_distribution'] = array('stereo'=>0, 'joint stereo'=>0, 'dual channel'=>0, 'mono'=>0);
  1259. $info['mpeg']['audio']['version_distribution'] = array('1'=>0, '2'=>0, '2.5'=>0);
  1260. if ($info['mpeg']['audio']['version'] == '1') {
  1261. if ($info['mpeg']['audio']['layer'] == 3) {
  1262. $info['mpeg']['audio']['bitrate_distribution'] = array('free'=>0, 32000=>0, 40000=>0, 48000=>0, 56000=>0, 64000=>0, 80000=>0, 96000=>0, 112000=>0, 128000=>0, 160000=>0, 192000=>0, 224000=>0, 256000=>0, 320000=>0);
  1263. } elseif ($info['mpeg']['audio']['layer'] == 2) {
  1264. $info['mpeg']['audio']['bitrate_distribution'] = array('free'=>0, 32000=>0, 48000=>0, 56000=>0, 64000=>0, 80000=>0, 96000=>0, 112000=>0, 128000=>0, 160000=>0, 192000=>0, 224000=>0, 256000=>0, 320000=>0, 384000=>0);
  1265. } elseif ($info['mpeg']['audio']['layer'] == 1) {
  1266. $info['mpeg']['audio']['bitrate_distribution'] = array('free'=>0, 32000=>0, 64000=>0, 96000=>0, 128000=>0, 160000=>0, 192000=>0, 224000=>0, 256000=>0, 288000=>0, 320000=>0, 352000=>0, 384000=>0, 416000=>0, 448000=>0);
  1267. }
  1268. } elseif ($info['mpeg']['audio']['layer'] == 1) {
  1269. $info['mpeg']['audio']['bitrate_distribution'] = array('free'=>0, 32000=>0, 48000=>0, 56000=>0, 64000=>0, 80000=>0, 96000=>0, 112000=>0, 128000=>0, 144000=>0, 160000=>0, 176000=>0, 192000=>0, 224000=>0, 256000=>0);
  1270. } else {
  1271. $info['mpeg']['audio']['bitrate_distribution'] = array('free'=>0, 8000=>0, 16000=>0, 24000=>0, 32000=>0, 40000=>0, 48000=>0, 56000=>0, 64000=>0, 80000=>0, 96000=>0, 112000=>0, 128000=>0, 144000=>0, 160000=>0);
  1272. }
  1273. $dummy = array('error'=>$info['error'], 'warning'=>$info['warning'], 'avdataend'=>$info['avdataend'], 'avdataoffset'=>$info['avdataoffset']);
  1274. $synchstartoffset = $info['avdataoffset'];
  1275. $this->fseek($info['avdataoffset']);
  1276. // you can play with these numbers:
  1277. $max_frames_scan = 50000;
  1278. $max_scan_segments = 10;
  1279. // don't play with these numbers:
  1280. $FastMode = false;
  1281. $SynchErrorsFound = 0;
  1282. $frames_scanned = 0;
  1283. $this_scan_segment = 0;
  1284. $frames_scan_per_segment = ceil($max_frames_scan / $max_scan_segments);
  1285. $pct_data_scanned = 0;
  1286. for ($current_segment = 0; $current_segment < $max_scan_segments; $current_segment++) {
  1287. $frames_scanned_this_segment = 0;
  1288. if ($this->ftell() >= $info['avdataend']) {
  1289. break;
  1290. }
  1291. $scan_start_offset[$current_segment] = max($this->ftell(), $info['avdataoffset'] + round($current_segment * (($info['avdataend'] - $info['avdataoffset']) / $max_scan_segments)));
  1292. if ($current_segment > 0) {
  1293. $this->fseek($scan_start_offset[$current_segment]);
  1294. $buffer_4k = $this->fread(4096);
  1295. for ($j = 0; $j < (strlen($buffer_4k) - 4); $j++) {
  1296. if (($buffer_4k{$j} == "\xFF") && ($buffer_4k{($j + 1)} > "\xE0")) { // synch detected
  1297. if ($this->decodeMPEGaudioHeader($scan_start_offset[$current_segment] + $j, $dummy, false, false, $FastMode)) {
  1298. $calculated_next_offset = $scan_start_offset[$current_segment] + $j + $dummy['mpeg']['audio']['framelength'];
  1299. if ($this->decodeMPEGaudioHeader($calculated_next_offset, $dummy, false, false, $FastMode)) {
  1300. $scan_start_offset[$current_segment] += $j;
  1301. break;
  1302. }
  1303. }
  1304. }
  1305. }
  1306. }
  1307. $synchstartoffset = $scan_start_offset[$current_segment];
  1308. while ($this->decodeMPEGaudioHeader($synchstartoffset, $dummy, false, false, $FastMode)) {
  1309. $FastMode = true;
  1310. $thisframebitrate = $MPEGaudioBitrateLookup[$MPEGaudioVersionLookup[$dummy['mpeg']['audio']['raw']['version']]][$MPEGaudioLayerLookup[$dummy['mpeg']['audio']['raw']['layer']]][$dummy['mpeg']['audio']['raw']['bitrate']];
  1311. if (empty($dummy['mpeg']['audio']['framelength'])) {
  1312. $SynchErrorsFound++;
  1313. $synchstartoffset++;
  1314. } else {
  1315. getid3_lib::safe_inc($info['mpeg']['audio']['bitrate_distribution'][$thisframebitrate]);
  1316. getid3_lib::safe_inc($info['mpeg']['audio']['stereo_distribution'][$dummy['mpeg']['audio']['channelmode']]);
  1317. getid3_lib::safe_inc($info['mpeg']['audio']['version_distribution'][$dummy['mpeg']['audio']['version']]);
  1318. $synchstartoffset += $dummy['mpeg']['audio']['framelength'];
  1319. }
  1320. $frames_scanned++;
  1321. if ($frames_scan_per_segment && (++$frames_scanned_this_segment >= $frames_scan_per_segment)) {
  1322. $this_pct_scanned = ($this->ftell() - $scan_start_offset[$current_segment]) / ($info['avdataend'] - $info['avdataoffset']);
  1323. if (($current_segment == 0) && (($this_pct_scanned * $max_scan_segments) >= 1)) {
  1324. // file likely contains < $max_frames_scan, just scan as one segment
  1325. $max_scan_segments = 1;
  1326. $frames_scan_per_segment = $max_frames_scan;
  1327. } else {
  1328. $pct_data_scanned += $this_pct_scanned;
  1329. break;
  1330. }
  1331. }
  1332. }
  1333. }
  1334. if ($pct_data_scanned > 0) {
  1335. $info['warning'][] = 'too many MPEG audio frames to scan, only scanned '.$frames_scanned.' frames in '.$max_scan_segments.' segments ('.number_format($pct_data_scanned * 100, 1).'% of file) and extrapolated distribution, playtime and bitrate may be incorrect.';
  1336. foreach ($info['mpeg']['audio'] as $key1 => $value1) {
  1337. if (!preg_match('#_distribution$#i', $key1)) {
  1338. continue;
  1339. }
  1340. foreach ($value1 as $key2 => $value2) {
  1341. $info['mpeg']['audio'][$key1][$key2] = round($value2 / $pct_data_scanned);
  1342. }
  1343. }
  1344. }
  1345. if ($SynchErrorsFound > 0) {
  1346. $info['warning'][] = 'Found '.$SynchErrorsFound.' synch errors in histogram analysis';
  1347. //return false;
  1348. }
  1349. $bittotal = 0;
  1350. $framecounter = 0;
  1351. foreach ($info['mpeg']['audio']['bitrate_distribution'] as $bitratevalue => $bitratecount) {
  1352. $framecounter += $bitratecount;
  1353. if ($bitratevalue != 'free') {
  1354. $bittotal += ($bitratevalue * $bitratecount);
  1355. }
  1356. }
  1357. if ($framecounter == 0) {
  1358. $info['error'][] = 'Corrupt MP3 file: framecounter == zero';
  1359. return false;
  1360. }
  1361. $info['mpeg']['audio']['frame_count'] = getid3_lib::CastAsInt($framecounter);
  1362. $info['mpeg']['audio']['bitrate'] = ($bittotal / $framecounter);
  1363. $info['audio']['bitrate'] = $info['mpeg']['audio']['bitrate'];
  1364. // Definitively set VBR vs CBR, even if the Xing/LAME/VBRI header says differently
  1365. $distinct_bitrates = 0;
  1366. foreach ($info['mpeg']['audio']['bitrate_distribution'] as $bitrate_value => $bitrate_count) {
  1367. if ($bitrate_count > 0) {
  1368. $distinct_bitrates++;
  1369. }
  1370. }
  1371. if ($distinct_bitrates > 1) {
  1372. $info['mpeg']['audio']['bitrate_mode'] = 'vbr';
  1373. } else {
  1374. $info['mpeg']['audio']['bitrate_mode'] = 'cbr';
  1375. }
  1376. $info['audio']['bitrate_mode'] = $info['mpeg']['audio']['bitrate_mode'];
  1377. }
  1378. break; // exit while()
  1379. }
  1380. }
  1381. $SynchSeekOffset++;
  1382. if (($avdataoffset + $SynchSeekOffset) >= $info['avdataend']) {
  1383. // end of file/data
  1384. if (empty($info['mpeg']['audio'])) {
  1385. $info['error'][] = 'could not find valid MPEG synch before end of file';
  1386. if (isset($info['audio']['bitrate'])) {
  1387. unset($info['audio']['bitrate']);
  1388. }
  1389. if (isset($info['mpeg']['audio'])) {
  1390. unset($info['mpeg']['audio']);
  1391. }
  1392. if (isset($info['mpeg']) && (!is_array($info['mpeg']) || empty($info['mpeg']))) {
  1393. unset($info['mpeg']);
  1394. }
  1395. return false;
  1396. }
  1397. break;
  1398. }
  1399. }
  1400. $info['audio']['channels'] = $info['mpeg']['audio']['channels'];
  1401. $info['audio']['channelmode'] = $info['mpeg']['audio']['channelmode'];
  1402. $info['audio']['sample_rate'] = $info['mpeg']['audio']['sample_rate'];
  1403. return true;
  1404. }
  1405. public static function MPEGaudioVersionArray() {
  1406. static $MPEGaudioVersion = array('2.5', false, '2', '1');
  1407. return $MPEGaudioVersion;
  1408. }
  1409. public static function MPEGaudioLayerArray() {
  1410. static $MPEGaudioLayer = array(false, 3, 2, 1);
  1411. return $MPEGaudioLayer;
  1412. }
  1413. public static function MPEGaudioBitrateArray() {
  1414. static $MPEGaudioBitrate;
  1415. if (empty($MPEGaudioBitrate)) {
  1416. $MPEGaudioBitrate = array (
  1417. '1' => array (1 => array('free', 32000, 64000, 96000, 128000, 160000, 192000, 224000, 256000, 288000, 320000, 352000, 384000, 416000, 448000),
  1418. 2 => array('free', 32000, 48000, 56000, 64000, 80000, 96000, 112000, 128000, 160000, 192000, 224000, 256000, 320000, 384000),
  1419. 3 => array('free', 32000, 40000, 48000, 56000, 64000, 80000, 96000, 112000, 128000, 160000, 192000, 224000, 256000, 320000)
  1420. ),
  1421. '2' => array (1 => array('free', 32000, 48000, 56000, 64000, 80000, 96000, 112000, 128000, 144000, 160000, 176000, 192000, 224000, 256000),
  1422. 2 => array('free', 8000, 16000, 24000, 32000, 40000, 48000, 56000, 64000, 80000, 96000, 112000, 128000, 144000, 160000),
  1423. )
  1424. );
  1425. $MPEGaudioBitrate['2'][3] = $MPEGaudioBitrate['2'][2];
  1426. $MPEGaudioBitrate['2.5'] = $MPEGaudioBitrate['2'];
  1427. }
  1428. return $MPEGaudioBitrate;
  1429. }
  1430. public static function MPEGaudioFrequencyArray() {
  1431. static $MPEGaudioFrequency;
  1432. if (empty($MPEGaudioFrequency)) {
  1433. $MPEGaudioFrequency = array (
  1434. '1' => array(44100, 48000, 32000),
  1435. '2' => array(22050, 24000, 16000),
  1436. '2.5' => array(11025, 12000, 8000)
  1437. );
  1438. }
  1439. return $MPEGaudioFrequency;
  1440. }
  1441. public static function MPEGaudioChannelModeArray() {
  1442. static $MPEGaudioChannelMode = array('stereo', 'joint stereo', 'dual channel', 'mono');
  1443. return $MPEGaudioChannelMode;
  1444. }
  1445. public static function MPEGaudioModeExtensionArray() {
  1446. static $MPEGaudioModeExtension;
  1447. if (empty($MPEGaudioModeExtension)) {
  1448. $MPEGaudioModeExtension = array (
  1449. 1 => array('4-31', '8-31', '12-31', '16-31'),
  1450. 2 => array('4-31', '8-31', '12-31', '16-31'),
  1451. 3 => array('', 'IS', 'MS', 'IS+MS')
  1452. );
  1453. }
  1454. return $MPEGaudioModeExtension;
  1455. }
  1456. public static function MPEGaudioEmphasisArray() {
  1457. static $MPEGaudioEmphasis = array('none', '50/15ms', false, 'CCIT J.17');
  1458. return $MPEGaudioEmphasis;
  1459. }
  1460. public static function MPEGaudioHeaderBytesValid($head4, $allowBitrate15=false) {
  1461. return self::MPEGaudioHeaderValid(self::MPEGaudioHeaderDecode($head4), false, $allowBitrate15);
  1462. }
  1463. public static function MPEGaudioHeaderValid($rawarray, $echoerrors=false, $allowBitrate15=false) {
  1464. if (($rawarray['synch'] & 0x0FFE) != 0x0FFE) {
  1465. return false;
  1466. }
  1467. static $MPEGaudioVersionLookup;
  1468. static $MPEGaudioLayerLookup;
  1469. static $MPEGaudioBitrateLookup;
  1470. static $MPEGaudioFrequencyLookup;
  1471. static $MPEGaudioChannelModeLookup;
  1472. static $MPEGaudioModeExtensionLookup;
  1473. static $MPEGaudioEmphasisLookup;
  1474. if (empty($MPEGaudioVersionLookup)) {
  1475. $MPEGaudioVersionLookup = self::MPEGaudioVersionArray();
  1476. $MPEGaudioLayerLookup = self::MPEGaudioLayerArray();
  1477. $MPEGaudioBitrateLookup = self::MPEGaudioBitrateArray();
  1478. $MPEGaudioFrequencyLookup = self::MPEGaudioFrequencyArray();
  1479. $MPEGaudioChannelModeLookup = self::MPEGaudioChannelModeArray();
  1480. $MPEGaudioModeExtensionLookup = self::MPEGaudioModeExtensionArray();
  1481. $MPEGaudioEmphasisLookup = self::MPEGaudioEmphasisArray();
  1482. }
  1483. if (isset($MPEGaudioVersionLookup[$rawarray['version']])) {
  1484. $decodedVersion = $MPEGaudioVersionLookup[$rawarray['version']];
  1485. } else {
  1486. echo ($echoerrors ? "\n".'invalid Version ('.$rawarray['version'].')' : '');
  1487. return false;
  1488. }
  1489. if (isset($MPEGaudioLayerLookup[$rawarray['layer']])) {
  1490. $decodedLayer = $MPEGaudioLayerLookup[$rawarray['layer']];
  1491. } else {
  1492. echo ($echoerrors ? "\n".'invalid Layer ('.$rawarray['layer'].')' : '');
  1493. return false;
  1494. }
  1495. if (!isset($MPEGaudioBitrateLookup[$decodedVersion][$decodedLayer][$rawarray['bitrate']])) {
  1496. echo ($echoerrors ? "\n".'invalid Bitrate ('.$rawarray['bitrate'].')' : '');
  1497. if ($rawarray['bitrate'] == 15) {
  1498. // known issue in LAME 3.90 - 3.93.1 where free-format has bitrate ID of 15 instead of 0
  1499. // let it go through here otherwise file will not be identified
  1500. if (!$allowBitrate15) {
  1501. return false;
  1502. }
  1503. } else {
  1504. return false;
  1505. }
  1506. }
  1507. if (!isset($MPEGaudioFrequencyLookup[$decodedVersion][$rawarray['sample_rate']])) {
  1508. echo ($echoerrors ? "\n".'invalid Frequency ('.$rawarray['sample_rate'].')' : '');
  1509. return false;
  1510. }
  1511. if (!isset($MPEGaudioChannelModeLookup[$rawarray['channelmode']])) {
  1512. echo ($echoerrors ? "\n".'invalid ChannelMode ('.$rawarray['channelmode'].')' : '');
  1513. return false;
  1514. }
  1515. if (!isset($MPEGaudioModeExtensionLookup[$decodedLayer][$rawarray['modeextension']])) {
  1516. echo ($echoerrors ? "\n".'invalid Mode Extension ('.$rawarray['modeextension'].')' : '');
  1517. return false;
  1518. }
  1519. if (!isset($MPEGaudioEmphasisLookup[$rawarray['emphasis']])) {
  1520. echo ($echoerrors ? "\n".'invalid Emphasis ('.$rawarray['emphasis'].')' : '');
  1521. return false;
  1522. }
  1523. // These are just either set or not set, you can't mess that up :)
  1524. // $rawarray['protection'];
  1525. // $rawarray['padding'];
  1526. // $rawarray['private'];
  1527. // $rawarray['copyright'];
  1528. // $rawarray['original'];
  1529. return true;
  1530. }
  1531. public static function MPEGaudioHeaderDecode($Header4Bytes) {
  1532. // AAAA AAAA AAAB BCCD EEEE FFGH IIJJ KLMM
  1533. // A - Frame sync (all bits set)
  1534. // B - MPEG Audio version ID
  1535. // C - Layer description
  1536. // D - Protection bit
  1537. // E - Bitrate index
  1538. // F - Sampling rate frequency index
  1539. // G - Padding bit
  1540. // H - Private bit
  1541. // I - Channel Mode
  1542. // J - Mode extension (Only if Joint stereo)
  1543. // K - Copyright
  1544. // L - Original
  1545. // M - Emphasis
  1546. if (strlen($Header4Bytes) != 4) {
  1547. return false;
  1548. }
  1549. $MPEGrawHeader['synch'] = (getid3_lib::BigEndian2Int(substr($Header4Bytes, 0, 2)) & 0xFFE0) >> 4;
  1550. $MPEGrawHeader['version'] = (ord($Header4Bytes{1}) & 0x18) >> 3; // BB
  1551. $MPEGrawHeader['layer'] = (ord($Header4Bytes{1}) & 0x06) >> 1; // CC
  1552. $MPEGrawHeader['protection'] = (ord($Header4Bytes{1}) & 0x01); // D
  1553. $MPEGrawHeader['bitrate'] = (ord($Header4Bytes{2}) & 0xF0) >> 4; // EEEE
  1554. $MPEGrawHeader['sample_rate'] = (ord($Header4Bytes{2}) & 0x0C) >> 2; // FF
  1555. $MPEGrawHeader['padding'] = (ord($Header4Bytes{2}) & 0x02) >> 1; // G
  1556. $MPEGrawHeader['private'] = (ord($Header4Bytes{2}) & 0x01); // H
  1557. $MPEGrawHeader['channelmode'] = (ord($Header4Bytes{3}) & 0xC0) >> 6; // II
  1558. $MPEGrawHeader['modeextension'] = (ord($Header4Bytes{3}) & 0x30) >> 4; // JJ
  1559. $MPEGrawHeader['copyright'] = (ord($Header4Bytes{3}) & 0x08) >> 3; // K
  1560. $MPEGrawHeader['original'] = (ord($Header4Bytes{3}) & 0x04) >> 2; // L
  1561. $MPEGrawHeader['emphasis'] = (ord($Header4Bytes{3}) & 0x03); // MM
  1562. return $MPEGrawHeader;
  1563. }
  1564. public static function MPEGaudioFrameLength(&$bitrate, &$version, &$layer, $padding, &$samplerate) {
  1565. static $AudioFrameLengthCache = array();
  1566. if (!isset($AudioFrameLengthCache[$bitrate][$version][$layer][$padding][$samplerate])) {
  1567. $AudioFrameLengthCache[$bitrate][$version][$layer][$padding][$samplerate] = false;
  1568. if ($bitrate != 'free') {
  1569. if ($version == '1') {
  1570. if ($layer == '1') {
  1571. // For Layer I slot is 32 bits long
  1572. $FrameLengthCoefficient = 48;
  1573. $SlotLength = 4;
  1574. } else { // Layer 2 / 3
  1575. // for Layer 2 and Layer 3 slot is 8 bits long.
  1576. $FrameLengthCoefficient = 144;
  1577. $SlotLength = 1;
  1578. }
  1579. } else { // MPEG-2 / MPEG-2.5
  1580. if ($layer == '1') {
  1581. // For Layer I slot is 32 bits long
  1582. $FrameLengthCoefficient = 24;
  1583. $SlotLength = 4;
  1584. } elseif ($layer == '2') {
  1585. // for Layer 2 and Layer 3 slot is 8 bits long.
  1586. $FrameLengthCoefficient = 144;
  1587. $SlotLength = 1;
  1588. } else { // layer 3
  1589. // for Layer 2 and Layer 3 slot is 8 bits long.
  1590. $FrameLengthCoefficient = 72;
  1591. $SlotLength = 1;
  1592. }
  1593. }
  1594. // FrameLengthInBytes = ((Coefficient * BitRate) / SampleRate) + Padding
  1595. if ($samplerate > 0) {
  1596. $NewFramelength = ($FrameLengthCoefficient * $bitrate) / $samplerate;
  1597. $NewFramelength = floor($NewFramelength / $SlotLength) * $SlotLength; // round to next-lower multiple of SlotLength (1 byte for Layer 2/3, 4 bytes for Layer I)
  1598. if ($padding) {
  1599. $NewFramelength += $SlotLength;
  1600. }
  1601. $AudioFrameLengthCache[$bitrate][$version][$layer][$padding][$samplerate] = (int) $NewFramelength;
  1602. }
  1603. }
  1604. }
  1605. return $AudioFrameLengthCache[$bitrate][$version][$layer][$padding][$samplerate];
  1606. }
  1607. public static function ClosestStandardMP3Bitrate($bit_rate) {
  1608. static $standard_bit_rates = array (320000, 256000, 224000, 192000, 160000, 128000, 112000, 96000, 80000, 64000, 56000, 48000, 40000, 32000, 24000, 16000, 8000);
  1609. static $bit_rate_table = array (0=>'-');
  1610. $round_bit_rate = intval(round($bit_rate, -3));
  1611. if (!isset($bit_rate_table[$round_bit_rate])) {
  1612. if ($round_bit_rate > max($standard_bit_rates)) {
  1613. $bit_rate_table[$round_bit_rate] = round($bit_rate, 2 - strlen($bit_rate));
  1614. } else {
  1615. $bit_rate_table[$round_bit_rate] = max($standard_bit_rates);
  1616. foreach ($standard_bit_rates as $standard_bit_rate) {
  1617. if ($round_bit_rate >= $standard_bit_rate + (($bit_rate_table[$round_bit_rate] - $standard_bit_rate) / 2)) {
  1618. break;
  1619. }
  1620. $bit_rate_table[$round_bit_rate] = $standard_bit_rate;
  1621. }
  1622. }
  1623. }
  1624. return $bit_rate_table[$round_bit_rate];
  1625. }
  1626. public static function XingVBRidOffset($version, $channelmode) {
  1627. static $XingVBRidOffsetCache = array();
  1628. if (empty($XingVBRidOffset)) {
  1629. $XingVBRidOffset = array (
  1630. '1' => array ('mono' => 0x15, // 4 + 17 = 21
  1631. 'stereo' => 0x24, // 4 + 32 = 36
  1632. 'joint stereo' => 0x24,
  1633. 'dual channel' => 0x24
  1634. ),
  1635. '2' => array ('mono' => 0x0D, // 4 + 9 = 13
  1636. 'stereo' => 0x15, // 4 + 17 = 21
  1637. 'joint stereo' => 0x15,
  1638. 'dual channel' => 0x15
  1639. ),
  1640. '2.5' => array ('mono' => 0x15,
  1641. 'stereo' => 0x15,
  1642. 'joint stereo' => 0x15,
  1643. 'dual channel' => 0x15
  1644. )
  1645. );
  1646. }
  1647. return $XingVBRidOffset[$version][$channelmode];
  1648. }
  1649. public static function LAMEvbrMethodLookup($VBRmethodID) {
  1650. static $LAMEvbrMethodLookup = array(
  1651. 0x00 => 'unknown',
  1652. 0x01 => 'cbr',
  1653. 0x02 => 'abr',
  1654. 0x03 => 'vbr-old / vbr-rh',
  1655. 0x04 => 'vbr-new / vbr-mtrh',
  1656. 0x05 => 'vbr-mt',
  1657. 0x06 => 'vbr (full vbr method 4)',
  1658. 0x08 => 'cbr (constant bitrate 2 pass)',
  1659. 0x09 => 'abr (2 pass)',
  1660. 0x0F => 'reserved'
  1661. );
  1662. return (isset($LAMEvbrMethodLookup[$VBRmethodID]) ? $LAMEvbrMethodLookup[$VBRmethodID] : '');
  1663. }
  1664. public static function LAMEmiscStereoModeLookup($StereoModeID) {
  1665. static $LAMEmiscStereoModeLookup = array(
  1666. 0 => 'mono',
  1667. 1 => 'stereo',
  1668. 2 => 'dual mono',
  1669. 3 => 'joint stereo',
  1670. 4 => 'forced stereo',
  1671. 5 => 'auto',
  1672. 6 => 'intensity stereo',
  1673. 7 => 'other'
  1674. );
  1675. return (isset($LAMEmiscStereoModeLookup[$StereoModeID]) ? $LAMEmiscStereoModeLookup[$StereoModeID] : '');
  1676. }
  1677. public static function LAMEmiscSourceSampleFrequencyLookup($SourceSampleFrequencyID) {
  1678. static $LAMEmiscSourceSampleFrequencyLookup = array(
  1679. 0 => '<= 32 kHz',
  1680. 1 => '44.1 kHz',
  1681. 2 => '48 kHz',
  1682. 3 => '> 48kHz'
  1683. );
  1684. return (isset($LAMEmiscSourceSampleFrequencyLookup[$SourceSampleFrequencyID]) ? $LAMEmiscSourceSampleFrequencyLookup[$SourceSampleFrequencyID] : '');
  1685. }
  1686. public static function LAMEsurroundInfoLookup($SurroundInfoID) {
  1687. static $LAMEsurroundInfoLookup = array(
  1688. 0 => 'no surround info',
  1689. 1 => 'DPL encoding',
  1690. 2 => 'DPL2 encoding',
  1691. 3 => 'Ambisonic encoding'
  1692. );
  1693. return (isset($LAMEsurroundInfoLookup[$SurroundInfoID]) ? $LAMEsurroundInfoLookup[$SurroundInfoID] : 'reserved');
  1694. }
  1695. public static function LAMEpresetUsedLookup($LAMEtag) {
  1696. if ($LAMEtag['preset_used_id'] == 0) {
  1697. // no preset used (LAME >=3.93)
  1698. // no preset recorded (LAME <3.93)
  1699. return '';
  1700. }
  1701. $LAMEpresetUsedLookup = array();
  1702. ///// THIS PART CANNOT BE STATIC .
  1703. for ($i = 8; $i <= 320; $i++) {
  1704. switch ($LAMEtag['vbr_method']) {
  1705. case 'cbr':
  1706. $LAMEpresetUsedLookup[$i] = '--alt-preset '.$LAMEtag['vbr_method'].' '.$i;
  1707. break;
  1708. case 'abr':
  1709. default: // other VBR modes shouldn't be here(?)
  1710. $LAMEpresetUsedLookup[$i] = '--alt-preset '.$i;
  1711. break;
  1712. }
  1713. }
  1714. // named old-style presets (studio, phone, voice, etc) are handled in GuessEncoderOptions()
  1715. // named alt-presets
  1716. $LAMEpresetUsedLookup[1000] = '--r3mix';
  1717. $LAMEpresetUsedLookup[1001] = '--alt-preset standard';
  1718. $LAMEpresetUsedLookup[1002] = '--alt-preset extreme';
  1719. $LAMEpresetUsedLookup[1003] = '--alt-preset insane';
  1720. $LAMEpresetUsedLookup[1004] = '--alt-preset fast standard';
  1721. $LAMEpresetUsedLookup[1005] = '--alt-preset fast extreme';
  1722. $LAMEpresetUsedLookup[1006] = '--alt-preset medium';
  1723. $LAMEpresetUsedLookup[1007] = '--alt-preset fast medium';
  1724. // LAME 3.94 additions/changes
  1725. $LAMEpresetUsedLookup[1010] = '--preset portable'; // 3.94a15 Oct 21 2003
  1726. $LAMEpresetUsedLookup[1015] = '--preset radio'; // 3.94a15 Oct 21 2003
  1727. $LAMEpresetUsedLookup[320] = '--preset insane'; // 3.94a15 Nov 12 2003
  1728. $LAMEpresetUsedLookup[410] = '-V9';
  1729. $LAMEpresetUsedLookup[420] = '-V8';
  1730. $LAMEpresetUsedLookup[440] = '-V6';
  1731. $LAMEpresetUsedLookup[430] = '--preset radio'; // 3.94a15 Nov 12 2003
  1732. $LAMEpresetUsedLookup[450] = '--preset '.(($LAMEtag['raw']['vbr_method'] == 4) ? 'fast ' : '').'portable'; // 3.94a15 Nov 12 2003
  1733. $LAMEpresetUsedLookup[460] = '--preset '.(($LAMEtag['raw']['vbr_method'] == 4) ? 'fast ' : '').'medium'; // 3.94a15 Nov 12 2003
  1734. $LAMEpresetUsedLookup[470] = '--r3mix'; // 3.94b1 Dec 18 2003
  1735. $LAMEpresetUsedLookup[480] = '--preset '.(($LAMEtag['raw']['vbr_method'] == 4) ? 'fast ' : '').'standard'; // 3.94a15 Nov 12 2003
  1736. $LAMEpresetUsedLookup[490] = '-V1';
  1737. $LAMEpresetUsedLookup[500] = '--preset '.(($LAMEtag['raw']['vbr_method'] == 4) ? 'fast ' : '').'extreme'; // 3.94a15 Nov 12 2003
  1738. return (isset($LAMEpresetUsedLookup[$LAMEtag['preset_used_id']]) ? $LAMEpresetUsedLookup[$LAMEtag['preset_used_id']] : 'new/unknown preset: '.$LAMEtag['preset_used_id'].' - report to info@getid3.org');
  1739. }
  1740. }