module.audio.mp3.php 100 KB

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