Geen omschrijving

module.audio.mp3.php 104KB

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