module.audio.mp3.php 105 KB

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