module.audio.mp3.php 101 KB

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