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