module.audio.mp3.php 97 KB

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