PageRenderTime 963ms CodeModel.GetById 103ms app.highlight 552ms RepoModel.GetById 77ms app.codeStats 1ms

/getid3/module.audio.mp3.php

https://bitbucket.org/holyfield/getid3
PHP | 2010 lines | 1430 code | 284 blank | 296 comment | 399 complexity | 4dfcc43a135d5600a396526410f4d65d MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1<?php
  2/////////////////////////////////////////////////////////////////
  3/// getID3() by James Heinrich <info@getid3.org>               //
  4//  available at http://getid3.sourceforge.net                 //
  5//            or http://www.getid3.org                         //
  6/////////////////////////////////////////////////////////////////
  7// See readme.txt for more details                             //
  8/////////////////////////////////////////////////////////////////
  9//                                                             //
 10// module.audio.mp3.php                                        //
 11// module for analyzing MP3 files                              //
 12// dependencies: NONE                                          //
 13//                                                            ///
 14/////////////////////////////////////////////////////////////////
 15
 16
 17// number of frames to scan to determine if MPEG-audio sequence is valid
 18// Lower this number to 5-20 for faster scanning
 19// Increase this number to 50+ for most accurate detection of valid VBR/CBR
 20// mpeg-audio streams
 21define('GETID3_MP3_VALID_CHECK_FRAMES', 35);
 22
 23
 24class getid3_mp3 extends getid3_handler
 25{
 26
 27	var $allow_bruteforce = false; // forces getID3() to scan the file byte-by-byte and log all the valid audio frame headers - extremely slow, unrecommended, but may provide data from otherwise-unusuable files
 28
 29	function Analyze() {
 30		$info = &$this->getid3->info;
 31
 32		$initialOffset = $info['avdataoffset'];
 33
 34		if (!$this->getOnlyMPEGaudioInfo($info['avdataoffset'])) {
 35			if ($this->allow_bruteforce) {
 36				$info['error'][] = 'Rescanning file in BruteForce mode';
 37				$this->getOnlyMPEGaudioInfoBruteForce($this->getid3->fp, $info);
 38			}
 39		}
 40
 41
 42		if (isset($info['mpeg']['audio']['bitrate_mode'])) {
 43			$info['audio']['bitrate_mode'] = strtolower($info['mpeg']['audio']['bitrate_mode']);
 44		}
 45
 46		if (((isset($info['id3v2']['headerlength']) && ($info['avdataoffset'] > $info['id3v2']['headerlength'])) || (!isset($info['id3v2']) && ($info['avdataoffset'] > 0) && ($info['avdataoffset'] != $initialOffset)))) {
 47
 48			$synchoffsetwarning = 'Unknown data before synch ';
 49			if (isset($info['id3v2']['headerlength'])) {
 50				$synchoffsetwarning .= '(ID3v2 header ends at '.$info['id3v2']['headerlength'].', then '.($info['avdataoffset'] - $info['id3v2']['headerlength']).' bytes garbage, ';
 51			} elseif ($initialOffset > 0) {
 52				$synchoffsetwarning .= '(should be at '.$initialOffset.', ';
 53			} else {
 54				$synchoffsetwarning .= '(should be at beginning of file, ';
 55			}
 56			$synchoffsetwarning .= 'synch detected at '.$info['avdataoffset'].')';
 57			if (isset($info['audio']['bitrate_mode']) && ($info['audio']['bitrate_mode'] == 'cbr')) {
 58
 59				if (!empty($info['id3v2']['headerlength']) && (($info['avdataoffset'] - $info['id3v2']['headerlength']) == $info['mpeg']['audio']['framelength'])) {
 60
 61					$synchoffsetwarning .= '. This is a known problem with some versions of LAME (3.90-3.92) DLL in CBR mode.';
 62					$info['audio']['codec'] = 'LAME';
 63					$CurrentDataLAMEversionString = 'LAME3.';
 64
 65				} elseif (empty($info['id3v2']['headerlength']) && ($info['avdataoffset'] == $info['mpeg']['audio']['framelength'])) {
 66
 67					$synchoffsetwarning .= '. This is a known problem with some versions of LAME (3.90 - 3.92) DLL in CBR mode.';
 68					$info['audio']['codec'] = 'LAME';
 69					$CurrentDataLAMEversionString = 'LAME3.';
 70
 71				}
 72
 73			}
 74			$info['warning'][] = $synchoffsetwarning;
 75
 76		}
 77
 78		if (isset($info['mpeg']['audio']['LAME'])) {
 79			$info['audio']['codec'] = 'LAME';
 80			if (!empty($info['mpeg']['audio']['LAME']['long_version'])) {
 81				$info['audio']['encoder'] = rtrim($info['mpeg']['audio']['LAME']['long_version'], "\x00");
 82			} elseif (!empty($info['mpeg']['audio']['LAME']['short_version'])) {
 83				$info['audio']['encoder'] = rtrim($info['mpeg']['audio']['LAME']['short_version'], "\x00");
 84			}
 85		}
 86
 87		$CurrentDataLAMEversionString = (!empty($CurrentDataLAMEversionString) ? $CurrentDataLAMEversionString : (isset($info['audio']['encoder']) ? $info['audio']['encoder'] : ''));
 88		if (!empty($CurrentDataLAMEversionString) && (substr($CurrentDataLAMEversionString, 0, 6) == 'LAME3.') && !preg_match('[0-9\)]', substr($CurrentDataLAMEversionString, -1))) {
 89			// a version number of LAME that does not end with a number like "LAME3.92"
 90			// or with a closing parenthesis like "LAME3.88 (alpha)"
 91			// or a version of LAME with the LAMEtag-not-filled-in-DLL-mode bug (3.90-3.92)
 92
 93			// not sure what the actual last frame length will be, but will be less than or equal to 1441
 94			$PossiblyLongerLAMEversion_FrameLength = 1441;
 95
 96			// Not sure what version of LAME this is - look in padding of last frame for longer version string
 97			$PossibleLAMEversionStringOffset = $info['avdataend'] - $PossiblyLongerLAMEversion_FrameLength;
 98			fseek($this->getid3->fp, $PossibleLAMEversionStringOffset);
 99			$PossiblyLongerLAMEversion_Data = fread($this->getid3->fp, $PossiblyLongerLAMEversion_FrameLength);
100			switch (substr($CurrentDataLAMEversionString, -1)) {
101				case 'a':
102				case 'b':
103					// "LAME3.94a" will have a longer version string of "LAME3.94 (alpha)" for example
104					// need to trim off "a" to match longer string
105					$CurrentDataLAMEversionString = substr($CurrentDataLAMEversionString, 0, -1);
106					break;
107			}
108			if (($PossiblyLongerLAMEversion_String = strstr($PossiblyLongerLAMEversion_Data, $CurrentDataLAMEversionString)) !== false) {
109				if (substr($PossiblyLongerLAMEversion_String, 0, strlen($CurrentDataLAMEversionString)) == $CurrentDataLAMEversionString) {
110					$PossiblyLongerLAMEversion_NewString = substr($PossiblyLongerLAMEversion_String, 0, strspn($PossiblyLongerLAMEversion_String, 'LAME0123456789., (abcdefghijklmnopqrstuvwxyzJFSOND)')); //"LAME3.90.3"  "LAME3.87 (beta 1, Sep 27 2000)" "LAME3.88 (beta)"
111					if (empty($info['audio']['encoder']) || (strlen($PossiblyLongerLAMEversion_NewString) > strlen($info['audio']['encoder']))) {
112						$info['audio']['encoder'] = $PossiblyLongerLAMEversion_NewString;
113					}
114				}
115			}
116		}
117		if (!empty($info['audio']['encoder'])) {
118			$info['audio']['encoder'] = rtrim($info['audio']['encoder'], "\x00 ");
119		}
120
121		switch (isset($info['mpeg']['audio']['layer']) ? $info['mpeg']['audio']['layer'] : '') {
122			case 1:
123			case 2:
124				$info['audio']['dataformat'] = 'mp'.$info['mpeg']['audio']['layer'];
125				break;
126		}
127		if (isset($info['fileformat']) && ($info['fileformat'] == 'mp3')) {
128			switch ($info['audio']['dataformat']) {
129				case 'mp1':
130				case 'mp2':
131				case 'mp3':
132					$info['fileformat'] = $info['audio']['dataformat'];
133					break;
134
135				default:
136					$info['warning'][] = 'Expecting [audio][dataformat] to be mp1/mp2/mp3 when fileformat == mp3, [audio][dataformat] actually "'.$info['audio']['dataformat'].'"';
137					break;
138			}
139		}
140
141		if (empty($info['fileformat'])) {
142			unset($info['fileformat']);
143			unset($info['audio']['bitrate_mode']);
144			unset($info['avdataoffset']);
145			unset($info['avdataend']);
146			return false;
147		}
148
149		$info['mime_type']         = 'audio/mpeg';
150		$info['audio']['lossless'] = false;
151
152		// Calculate playtime
153		if (!isset($info['playtime_seconds']) && isset($info['audio']['bitrate']) && ($info['audio']['bitrate'] > 0)) {
154			$info['playtime_seconds'] = ($info['avdataend'] - $info['avdataoffset']) * 8 / $info['audio']['bitrate'];
155		}
156
157		$info['audio']['encoder_options'] = $this->GuessEncoderOptions();
158
159		return true;
160	}
161
162
163	function GuessEncoderOptions() {
164		// shortcuts
165		$info = &$this->getid3->info;
166		if (!empty($info['mpeg']['audio'])) {
167			$thisfile_mpeg_audio = &$info['mpeg']['audio'];
168			if (!empty($thisfile_mpeg_audio['LAME'])) {
169				$thisfile_mpeg_audio_lame = &$thisfile_mpeg_audio['LAME'];
170			}
171		}
172
173		$encoder_options = '';
174		static $NamedPresetBitrates = array(16, 24, 40, 56, 112, 128, 160, 192, 256);
175
176		if (isset($thisfile_mpeg_audio['VBR_method']) && ($thisfile_mpeg_audio['VBR_method'] == 'Fraunhofer') && !empty($thisfile_mpeg_audio['VBR_quality'])) {
177
178			$encoder_options = 'VBR q'.$thisfile_mpeg_audio['VBR_quality'];
179
180		} elseif (!empty($thisfile_mpeg_audio_lame['preset_used']) && (!in_array($thisfile_mpeg_audio_lame['preset_used_id'], $NamedPresetBitrates))) {
181
182			$encoder_options = $thisfile_mpeg_audio_lame['preset_used'];
183
184		} elseif (!empty($thisfile_mpeg_audio_lame['vbr_quality'])) {
185
186			static $KnownEncoderValues = array();
187			if (empty($KnownEncoderValues)) {
188
189				//$KnownEncoderValues[abrbitrate_minbitrate][vbr_quality][raw_vbr_method][raw_noise_shaping][raw_stereo_mode][ath_type][lowpass_frequency] = 'preset name';
190				$KnownEncoderValues[0xFF][58][1][1][3][2][20500] = '--alt-preset insane';        // 3.90,   3.90.1, 3.92
191				$KnownEncoderValues[0xFF][58][1][1][3][2][20600] = '--alt-preset insane';        // 3.90.2, 3.90.3, 3.91
192				$KnownEncoderValues[0xFF][57][1][1][3][4][20500] = '--alt-preset insane';        // 3.94,   3.95
193				$KnownEncoderValues['**'][78][3][2][3][2][19500] = '--alt-preset extreme';       // 3.90,   3.90.1, 3.92
194				$KnownEncoderValues['**'][78][3][2][3][2][19600] = '--alt-preset extreme';       // 3.90.2, 3.91
195				$KnownEncoderValues['**'][78][3][1][3][2][19600] = '--alt-preset extreme';       // 3.90.3
196				$KnownEncoderValues['**'][78][4][2][3][2][19500] = '--alt-preset fast extreme';  // 3.90,   3.90.1, 3.92
197				$KnownEncoderValues['**'][78][4][2][3][2][19600] = '--alt-preset fast extreme';  // 3.90.2, 3.90.3, 3.91
198				$KnownEncoderValues['**'][78][3][2][3][4][19000] = '--alt-preset standard';      // 3.90,   3.90.1, 3.90.2, 3.91, 3.92
199				$KnownEncoderValues['**'][78][3][1][3][4][19000] = '--alt-preset standard';      // 3.90.3
200				$KnownEncoderValues['**'][78][4][2][3][4][19000] = '--alt-preset fast standard'; // 3.90,   3.90.1, 3.90.2, 3.91, 3.92
201				$KnownEncoderValues['**'][78][4][1][3][4][19000] = '--alt-preset fast standard'; // 3.90.3
202				$KnownEncoderValues['**'][88][4][1][3][3][19500] = '--r3mix';                    // 3.90,   3.90.1, 3.92
203				$KnownEncoderValues['**'][88][4][1][3][3][19600] = '--r3mix';                    // 3.90.2, 3.90.3, 3.91
204				$KnownEncoderValues['**'][67][4][1][3][4][18000] = '--r3mix';                    // 3.94,   3.95
205				$KnownEncoderValues['**'][68][3][2][3][4][18000] = '--alt-preset medium';        // 3.90.3
206				$KnownEncoderValues['**'][68][4][2][3][4][18000] = '--alt-preset fast medium';   // 3.90.3
207
208				$KnownEncoderValues[0xFF][99][1][1][1][2][0]     = '--preset studio';            // 3.90,   3.90.1, 3.90.2, 3.91, 3.92
209				$KnownEncoderValues[0xFF][58][2][1][3][2][20600] = '--preset studio';            // 3.90.3, 3.93.1
210				$KnownEncoderValues[0xFF][58][2][1][3][2][20500] = '--preset studio';            // 3.93
211				$KnownEncoderValues[0xFF][57][2][1][3][4][20500] = '--preset studio';            // 3.94,   3.95
212				$KnownEncoderValues[0xC0][88][1][1][1][2][0]     = '--preset cd';                // 3.90,   3.90.1, 3.90.2,   3.91, 3.92
213				$KnownEncoderValues[0xC0][58][2][2][3][2][19600] = '--preset cd';                // 3.90.3, 3.93.1
214				$KnownEncoderValues[0xC0][58][2][2][3][2][19500] = '--preset cd';                // 3.93
215				$KnownEncoderValues[0xC0][57][2][1][3][4][19500] = '--preset cd';                // 3.94,   3.95
216				$KnownEncoderValues[0xA0][78][1][1][3][2][18000] = '--preset hifi';              // 3.90,   3.90.1, 3.90.2,   3.91, 3.92
217				$KnownEncoderValues[0xA0][58][2][2][3][2][18000] = '--preset hifi';              // 3.90.3, 3.93,   3.93.1
218				$KnownEncoderValues[0xA0][57][2][1][3][4][18000] = '--preset hifi';              // 3.94,   3.95
219				$KnownEncoderValues[0x80][67][1][1][3][2][18000] = '--preset tape';              // 3.90,   3.90.1, 3.90.2,   3.91, 3.92
220				$KnownEncoderValues[0x80][67][1][1][3][2][15000] = '--preset radio';             // 3.90,   3.90.1, 3.90.2,   3.91, 3.92
221				$KnownEncoderValues[0x70][67][1][1][3][2][15000] = '--preset fm';                // 3.90,   3.90.1, 3.90.2,   3.91, 3.92
222				$KnownEncoderValues[0x70][58][2][2][3][2][16000] = '--preset tape/radio/fm';     // 3.90.3, 3.93,   3.93.1
223				$KnownEncoderValues[0x70][57][2][1][3][4][16000] = '--preset tape/radio/fm';     // 3.94,   3.95
224				$KnownEncoderValues[0x38][58][2][2][0][2][10000] = '--preset voice';             // 3.90.3, 3.93,   3.93.1
225				$KnownEncoderValues[0x38][57][2][1][0][4][15000] = '--preset voice';             // 3.94,   3.95
226				$KnownEncoderValues[0x38][57][2][1][0][4][16000] = '--preset voice';             // 3.94a14
227				$KnownEncoderValues[0x28][65][1][1][0][2][7500]  = '--preset mw-us';             // 3.90,   3.90.1, 3.92
228				$KnownEncoderValues[0x28][65][1][1][0][2][7600]  = '--preset mw-us';             // 3.90.2, 3.91
229				$KnownEncoderValues[0x28][58][2][2][0][2][7000]  = '--preset mw-us';             // 3.90.3, 3.93,   3.93.1
230				$KnownEncoderValues[0x28][57][2][1][0][4][10500] = '--preset mw-us';             // 3.94,   3.95
231				$KnownEncoderValues[0x28][57][2][1][0][4][11200] = '--preset mw-us';             // 3.94a14
232				$KnownEncoderValues[0x28][57][2][1][0][4][8800]  = '--preset mw-us';             // 3.94a15
233				$KnownEncoderValues[0x18][58][2][2][0][2][4000]  = '--preset phon+/lw/mw-eu/sw'; // 3.90.3, 3.93.1
234				$KnownEncoderValues[0x18][58][2][2][0][2][3900]  = '--preset phon+/lw/mw-eu/sw'; // 3.93
235				$KnownEncoderValues[0x18][57][2][1][0][4][5900]  = '--preset phon+/lw/mw-eu/sw'; // 3.94,   3.95
236				$KnownEncoderValues[0x18][57][2][1][0][4][6200]  = '--preset phon+/lw/mw-eu/sw'; // 3.94a14
237				$KnownEncoderValues[0x18][57][2][1][0][4][3200]  = '--preset phon+/lw/mw-eu/sw'; // 3.94a15
238				$KnownEncoderValues[0x10][58][2][2][0][2][3800]  = '--preset phone';             // 3.90.3, 3.93.1
239				$KnownEncoderValues[0x10][58][2][2][0][2][3700]  = '--preset phone';             // 3.93
240				$KnownEncoderValues[0x10][57][2][1][0][4][5600]  = '--preset phone';             // 3.94,   3.95
241			}
242
243			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']])) {
244
245				$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']];
246
247			} 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']])) {
248
249				$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']];
250
251			} elseif ($info['audio']['bitrate_mode'] == 'vbr') {
252
253				// http://gabriel.mp3-tech.org/mp3infotag.html
254				// int    Quality = (100 - 10 * gfp->VBR_q - gfp->quality)h
255
256
257				$LAME_V_value = 10 - ceil($thisfile_mpeg_audio_lame['vbr_quality'] / 10);
258				$LAME_q_value = 100 - $thisfile_mpeg_audio_lame['vbr_quality'] - ($LAME_V_value * 10);
259				$encoder_options = '-V'.$LAME_V_value.' -q'.$LAME_q_value;
260
261			} elseif ($info['audio']['bitrate_mode'] == 'cbr') {
262
263				$encoder_options = strtoupper($info['audio']['bitrate_mode']).ceil($info['audio']['bitrate'] / 1000);
264
265			} else {
266
267				$encoder_options = strtoupper($info['audio']['bitrate_mode']);
268
269			}
270
271		} elseif (!empty($thisfile_mpeg_audio_lame['bitrate_abr'])) {
272
273			$encoder_options = 'ABR'.$thisfile_mpeg_audio_lame['bitrate_abr'];
274
275		} elseif (!empty($info['audio']['bitrate'])) {
276
277			if ($info['audio']['bitrate_mode'] == 'cbr') {
278				$encoder_options = strtoupper($info['audio']['bitrate_mode']).ceil($info['audio']['bitrate'] / 1000);
279			} else {
280				$encoder_options = strtoupper($info['audio']['bitrate_mode']);
281			}
282
283		}
284		if (!empty($thisfile_mpeg_audio_lame['bitrate_min'])) {
285			$encoder_options .= ' -b'.$thisfile_mpeg_audio_lame['bitrate_min'];
286		}
287
288		if (!empty($thisfile_mpeg_audio_lame['encoding_flags']['nogap_prev']) || !empty($thisfile_mpeg_audio_lame['encoding_flags']['nogap_next'])) {
289			$encoder_options .= ' --nogap';
290		}
291
292		if (!empty($thisfile_mpeg_audio_lame['lowpass_frequency'])) {
293			$ExplodedOptions = explode(' ', $encoder_options, 4);
294			if ($ExplodedOptions[0] == '--r3mix') {
295				$ExplodedOptions[1] = 'r3mix';
296			}
297			switch ($ExplodedOptions[0]) {
298				case '--preset':
299				case '--alt-preset':
300				case '--r3mix':
301					if ($ExplodedOptions[1] == 'fast') {
302						$ExplodedOptions[1] .= ' '.$ExplodedOptions[2];
303					}
304					switch ($ExplodedOptions[1]) {
305						case 'portable':
306						case 'medium':
307						case 'standard':
308						case 'extreme':
309						case 'insane':
310						case 'fast portable':
311						case 'fast medium':
312						case 'fast standard':
313						case 'fast extreme':
314						case 'fast insane':
315						case 'r3mix':
316							static $ExpectedLowpass = array(
317									'insane|20500'        => 20500,
318									'insane|20600'        => 20600,  // 3.90.2, 3.90.3, 3.91
319									'medium|18000'        => 18000,
320									'fast medium|18000'   => 18000,
321									'extreme|19500'       => 19500,  // 3.90,   3.90.1, 3.92, 3.95
322									'extreme|19600'       => 19600,  // 3.90.2, 3.90.3, 3.91, 3.93.1
323									'fast extreme|19500'  => 19500,  // 3.90,   3.90.1, 3.92, 3.95
324									'fast extreme|19600'  => 19600,  // 3.90.2, 3.90.3, 3.91, 3.93.1
325									'standard|19000'      => 19000,
326									'fast standard|19000' => 19000,
327									'r3mix|19500'         => 19500,  // 3.90,   3.90.1, 3.92
328									'r3mix|19600'         => 19600,  // 3.90.2, 3.90.3, 3.91
329									'r3mix|18000'         => 18000,  // 3.94,   3.95
330								);
331							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))) {
332								$encoder_options .= ' --lowpass '.$thisfile_mpeg_audio_lame['lowpass_frequency'];
333							}
334							break;
335
336						default:
337							break;
338					}
339					break;
340			}
341		}
342
343		if (isset($thisfile_mpeg_audio_lame['raw']['source_sample_freq'])) {
344			if (($thisfile_mpeg_audio['sample_rate'] == 44100) && ($thisfile_mpeg_audio_lame['raw']['source_sample_freq'] != 1)) {
345				$encoder_options .= ' --resample 44100';
346			} elseif (($thisfile_mpeg_audio['sample_rate'] == 48000) && ($thisfile_mpeg_audio_lame['raw']['source_sample_freq'] != 2)) {
347				$encoder_options .= ' --resample 48000';
348			} elseif ($thisfile_mpeg_audio['sample_rate'] < 44100) {
349				switch ($thisfile_mpeg_audio_lame['raw']['source_sample_freq']) {
350					case 0: // <= 32000
351						// may or may not be same as source frequency - ignore
352						break;
353					case 1: // 44100
354					case 2: // 48000
355					case 3: // 48000+
356						$ExplodedOptions = explode(' ', $encoder_options, 4);
357						switch ($ExplodedOptions[0]) {
358							case '--preset':
359							case '--alt-preset':
360								switch ($ExplodedOptions[1]) {
361									case 'fast':
362									case 'portable':
363									case 'medium':
364									case 'standard':
365									case 'extreme':
366									case 'insane':
367										$encoder_options .= ' --resample '.$thisfile_mpeg_audio['sample_rate'];
368										break;
369
370									default:
371										static $ExpectedResampledRate = array(
372												'phon+/lw/mw-eu/sw|16000' => 16000,
373												'mw-us|24000'             => 24000, // 3.95
374												'mw-us|32000'             => 32000, // 3.93
375												'mw-us|16000'             => 16000, // 3.92
376												'phone|16000'             => 16000,
377												'phone|11025'             => 11025, // 3.94a15
378												'radio|32000'             => 32000, // 3.94a15
379												'fm/radio|32000'          => 32000, // 3.92
380												'fm|32000'                => 32000, // 3.90
381												'voice|32000'             => 32000);
382										if (!isset($ExpectedResampledRate[$ExplodedOptions[1].'|'.$thisfile_mpeg_audio['sample_rate']])) {
383											$encoder_options .= ' --resample '.$thisfile_mpeg_audio['sample_rate'];
384										}
385										break;
386								}
387								break;
388
389							case '--r3mix':
390							default:
391								$encoder_options .= ' --resample '.$thisfile_mpeg_audio['sample_rate'];
392								break;
393						}
394						break;
395				}
396			}
397		}
398		if (empty($encoder_options) && !empty($info['audio']['bitrate']) && !empty($info['audio']['bitrate_mode'])) {
399			//$encoder_options = strtoupper($info['audio']['bitrate_mode']).ceil($info['audio']['bitrate'] / 1000);
400			$encoder_options = strtoupper($info['audio']['bitrate_mode']);
401		}
402
403		return $encoder_options;
404	}
405
406
407	function decodeMPEGaudioHeader($offset, &$info, $recursivesearch=true, $ScanAsCBR=false, $FastMPEGheaderScan=false) {
408		static $MPEGaudioVersionLookup;
409		static $MPEGaudioLayerLookup;
410		static $MPEGaudioBitrateLookup;
411		static $MPEGaudioFrequencyLookup;
412		static $MPEGaudioChannelModeLookup;
413		static $MPEGaudioModeExtensionLookup;
414		static $MPEGaudioEmphasisLookup;
415		if (empty($MPEGaudioVersionLookup)) {
416			$MPEGaudioVersionLookup       = getid3_mp3::MPEGaudioVersionArray();
417			$MPEGaudioLayerLookup         = getid3_mp3::MPEGaudioLayerArray();
418			$MPEGaudioBitrateLookup       = getid3_mp3::MPEGaudioBitrateArray();
419			$MPEGaudioFrequencyLookup     = getid3_mp3::MPEGaudioFrequencyArray();
420			$MPEGaudioChannelModeLookup   = getid3_mp3::MPEGaudioChannelModeArray();
421			$MPEGaudioModeExtensionLookup = getid3_mp3::MPEGaudioModeExtensionArray();
422			$MPEGaudioEmphasisLookup      = getid3_mp3::MPEGaudioEmphasisArray();
423		}
424
425		if (fseek($this->getid3->fp, $offset, SEEK_SET) != 0) {
426			$info['error'][] = 'decodeMPEGaudioHeader() failed to seek to next offset at '.$offset;
427			return false;
428		}
429		//$headerstring = fread($this->getid3->fp, 1441); // worst-case max length = 32kHz @ 320kbps layer 3 = 1441 bytes/frame
430		$headerstring = fread($this->getid3->fp, 226); // LAME header at offset 36 + 190 bytes of Xing/LAME data
431
432		// MP3 audio frame structure:
433		// $aa $aa $aa $aa [$bb $bb] $cc...
434		// where $aa..$aa is the four-byte mpeg-audio header (below)
435		// $bb $bb is the optional 2-byte CRC
436		// and $cc... is the audio data
437
438		$head4 = substr($headerstring, 0, 4);
439
440		static $MPEGaudioHeaderDecodeCache = array();
441		if (isset($MPEGaudioHeaderDecodeCache[$head4])) {
442			$MPEGheaderRawArray = $MPEGaudioHeaderDecodeCache[$head4];
443		} else {
444			$MPEGheaderRawArray = getid3_mp3::MPEGaudioHeaderDecode($head4);
445			$MPEGaudioHeaderDecodeCache[$head4] = $MPEGheaderRawArray;
446		}
447
448		static $MPEGaudioHeaderValidCache = array();
449		if (!isset($MPEGaudioHeaderValidCache[$head4])) { // Not in cache
450			//$MPEGaudioHeaderValidCache[$head4] = getid3_mp3::MPEGaudioHeaderValid($MPEGheaderRawArray, false, true);  // allow badly-formatted freeformat (from LAME 3.90 - 3.93.1)
451			$MPEGaudioHeaderValidCache[$head4] = getid3_mp3::MPEGaudioHeaderValid($MPEGheaderRawArray, false, false);
452		}
453
454		// shortcut
455		if (!isset($info['mpeg']['audio'])) {
456			$info['mpeg']['audio'] = array();
457		}
458		$thisfile_mpeg_audio = &$info['mpeg']['audio'];
459
460
461		if ($MPEGaudioHeaderValidCache[$head4]) {
462			$thisfile_mpeg_audio['raw'] = $MPEGheaderRawArray;
463		} else {
464			$info['error'][] = 'Invalid MPEG audio header ('.getid3_lib::PrintHexBytes($head4).') at offset '.$offset;
465			return false;
466		}
467
468		if (!$FastMPEGheaderScan) {
469			$thisfile_mpeg_audio['version']       = $MPEGaudioVersionLookup[$thisfile_mpeg_audio['raw']['version']];
470			$thisfile_mpeg_audio['layer']         = $MPEGaudioLayerLookup[$thisfile_mpeg_audio['raw']['layer']];
471
472			$thisfile_mpeg_audio['channelmode']   = $MPEGaudioChannelModeLookup[$thisfile_mpeg_audio['raw']['channelmode']];
473			$thisfile_mpeg_audio['channels']      = (($thisfile_mpeg_audio['channelmode'] == 'mono') ? 1 : 2);
474			$thisfile_mpeg_audio['sample_rate']   = $MPEGaudioFrequencyLookup[$thisfile_mpeg_audio['version']][$thisfile_mpeg_audio['raw']['sample_rate']];
475			$thisfile_mpeg_audio['protection']    = !$thisfile_mpeg_audio['raw']['protection'];
476			$thisfile_mpeg_audio['private']       = (bool) $thisfile_mpeg_audio['raw']['private'];
477			$thisfile_mpeg_audio['modeextension'] = $MPEGaudioModeExtensionLookup[$thisfile_mpeg_audio['layer']][$thisfile_mpeg_audio['raw']['modeextension']];
478			$thisfile_mpeg_audio['copyright']     = (bool) $thisfile_mpeg_audio['raw']['copyright'];
479			$thisfile_mpeg_audio['original']      = (bool) $thisfile_mpeg_audio['raw']['original'];
480			$thisfile_mpeg_audio['emphasis']      = $MPEGaudioEmphasisLookup[$thisfile_mpeg_audio['raw']['emphasis']];
481
482			$info['audio']['channels']    = $thisfile_mpeg_audio['channels'];
483			$info['audio']['sample_rate'] = $thisfile_mpeg_audio['sample_rate'];
484
485			if ($thisfile_mpeg_audio['protection']) {
486				$thisfile_mpeg_audio['crc'] = getid3_lib::BigEndian2Int(substr($headerstring, 4, 2));
487			}
488		}
489
490		if ($thisfile_mpeg_audio['raw']['bitrate'] == 15) {
491			// http://www.hydrogenaudio.org/?act=ST&f=16&t=9682&st=0
492			$info['warning'][] = 'Invalid bitrate index (15), this is a known bug in free-format MP3s encoded by LAME v3.90 - 3.93.1';
493			$thisfile_mpeg_audio['raw']['bitrate'] = 0;
494		}
495		$thisfile_mpeg_audio['padding'] = (bool) $thisfile_mpeg_audio['raw']['padding'];
496		$thisfile_mpeg_audio['bitrate'] = $MPEGaudioBitrateLookup[$thisfile_mpeg_audio['version']][$thisfile_mpeg_audio['layer']][$thisfile_mpeg_audio['raw']['bitrate']];
497
498		if (($thisfile_mpeg_audio['bitrate'] == 'free') && ($offset == $info['avdataoffset'])) {
499			// only skip multiple frame check if free-format bitstream found at beginning of file
500			// otherwise is quite possibly simply corrupted data
501			$recursivesearch = false;
502		}
503
504		// For Layer 2 there are some combinations of bitrate and mode which are not allowed.
505		if (!$FastMPEGheaderScan && ($thisfile_mpeg_audio['layer'] == '2')) {
506
507			$info['audio']['dataformat'] = 'mp2';
508			switch ($thisfile_mpeg_audio['channelmode']) {
509
510				case 'mono':
511					if (($thisfile_mpeg_audio['bitrate'] == 'free') || ($thisfile_mpeg_audio['bitrate'] <= 192000)) {
512						// these are ok
513					} else {
514						$info['error'][] = $thisfile_mpeg_audio['bitrate'].'kbps not allowed in Layer 2, '.$thisfile_mpeg_audio['channelmode'].'.';
515						return false;
516					}
517					break;
518
519				case 'stereo':
520				case 'joint stereo':
521				case 'dual channel':
522					if (($thisfile_mpeg_audio['bitrate'] == 'free') || ($thisfile_mpeg_audio['bitrate'] == 64000) || ($thisfile_mpeg_audio['bitrate'] >= 96000)) {
523						// these are ok
524					} else {
525						$info['error'][] = intval(round($thisfile_mpeg_audio['bitrate'] / 1000)).'kbps not allowed in Layer 2, '.$thisfile_mpeg_audio['channelmode'].'.';
526						return false;
527					}
528					break;
529
530			}
531
532		}
533
534
535		if ($info['audio']['sample_rate'] > 0) {
536			$thisfile_mpeg_audio['framelength'] = getid3_mp3::MPEGaudioFrameLength($thisfile_mpeg_audio['bitrate'], $thisfile_mpeg_audio['version'], $thisfile_mpeg_audio['layer'], (int) $thisfile_mpeg_audio['padding'], $info['audio']['sample_rate']);
537		}
538
539		$nextframetestoffset = $offset + 1;
540		if ($thisfile_mpeg_audio['bitrate'] != 'free') {
541
542			$info['audio']['bitrate'] = $thisfile_mpeg_audio['bitrate'];
543
544			if (isset($thisfile_mpeg_audio['framelength'])) {
545				$nextframetestoffset = $offset + $thisfile_mpeg_audio['framelength'];
546			} else {
547				$info['error'][] = 'Frame at offset('.$offset.') is has an invalid frame length.';
548				return false;
549			}
550
551		}
552
553		$ExpectedNumberOfAudioBytes = 0;
554
555		////////////////////////////////////////////////////////////////////////////////////
556		// Variable-bitrate headers
557
558		if (substr($headerstring, 4 + 32, 4) == 'VBRI') {
559			// Fraunhofer VBR header is hardcoded 'VBRI' at offset 0x24 (36)
560			// specs taken from http://minnie.tuhs.org/pipermail/mp3encoder/2001-January/001800.html
561
562			$thisfile_mpeg_audio['bitrate_mode'] = 'vbr';
563			$thisfile_mpeg_audio['VBR_method']   = 'Fraunhofer';
564			$info['audio']['codec']                = 'Fraunhofer';
565
566			$SideInfoData = substr($headerstring, 4 + 2, 32);
567
568			$FraunhoferVBROffset = 36;
569
570			$thisfile_mpeg_audio['VBR_encoder_version']     = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset +  4, 2)); // VbriVersion
571			$thisfile_mpeg_audio['VBR_encoder_delay']       = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset +  6, 2)); // VbriDelay
572			$thisfile_mpeg_audio['VBR_quality']             = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset +  8, 2)); // VbriQuality
573			$thisfile_mpeg_audio['VBR_bytes']               = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 10, 4)); // VbriStreamBytes
574			$thisfile_mpeg_audio['VBR_frames']              = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 14, 4)); // VbriStreamFrames
575			$thisfile_mpeg_audio['VBR_seek_offsets']        = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 18, 2)); // VbriTableSize
576			$thisfile_mpeg_audio['VBR_seek_scale']          = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 20, 2)); // VbriTableScale
577			$thisfile_mpeg_audio['VBR_entry_bytes']         = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 22, 2)); // VbriEntryBytes
578			$thisfile_mpeg_audio['VBR_entry_frames']        = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 24, 2)); // VbriEntryFrames
579
580			$ExpectedNumberOfAudioBytes = $thisfile_mpeg_audio['VBR_bytes'];
581
582			$previousbyteoffset = $offset;
583			for ($i = 0; $i < $thisfile_mpeg_audio['VBR_seek_offsets']; $i++) {
584				$Fraunhofer_OffsetN = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset, $thisfile_mpeg_audio['VBR_entry_bytes']));
585				$FraunhoferVBROffset += $thisfile_mpeg_audio['VBR_entry_bytes'];
586				$thisfile_mpeg_audio['VBR_offsets_relative'][$i] = ($Fraunhofer_OffsetN * $thisfile_mpeg_audio['VBR_seek_scale']);
587				$thisfile_mpeg_audio['VBR_offsets_absolute'][$i] = ($Fraunhofer_OffsetN * $thisfile_mpeg_audio['VBR_seek_scale']) + $previousbyteoffset;
588				$previousbyteoffset += $Fraunhofer_OffsetN;
589			}
590
591
592		} else {
593
594			// Xing VBR header is hardcoded 'Xing' at a offset 0x0D (13), 0x15 (21) or 0x24 (36)
595			// depending on MPEG layer and number of channels
596
597			$VBRidOffset = getid3_mp3::XingVBRidOffset($thisfile_mpeg_audio['version'], $thisfile_mpeg_audio['channelmode']);
598			$SideInfoData = substr($headerstring, 4 + 2, $VBRidOffset - 4);
599
600			if ((substr($headerstring, $VBRidOffset, strlen('Xing')) == 'Xing') || (substr($headerstring, $VBRidOffset, strlen('Info')) == 'Info')) {
601				// 'Xing' is traditional Xing VBR frame
602				// 'Info' is LAME-encoded CBR (This was done to avoid CBR files to be recognized as traditional Xing VBR files by some decoders.)
603				// 'Info' *can* legally be used to specify a VBR file as well, however.
604
605				// http://www.multiweb.cz/twoinches/MP3inside.htm
606				//00..03 = "Xing" or "Info"
607				//04..07 = Flags:
608				//  0x01  Frames Flag     set if value for number of frames in file is stored
609				//  0x02  Bytes Flag      set if value for filesize in bytes is stored
610				//  0x04  TOC Flag        set if values for TOC are stored
611				//  0x08  VBR Scale Flag  set if values for VBR scale is stored
612				//08..11  Frames: Number of frames in file (including the first Xing/Info one)
613				//12..15  Bytes:  File length in Bytes
614				//16..115  TOC (Table of Contents):
615				//  Contains of 100 indexes (one Byte length) for easier lookup in file. Approximately solves problem with moving inside file.
616				//  Each Byte has a value according this formula:
617				//  (TOC[i] / 256) * fileLenInBytes
618				//  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:
619				//  TOC[(60/240)*100] = TOC[25]
620				//  and corresponding Byte in file is then approximately at:
621				//  (TOC[25]/256) * 5000000
622				//116..119  VBR Scale
623
624
625				// should be safe to leave this at 'vbr' and let it be overriden to 'cbr' if a CBR preset/mode is used by LAME
626//				if (substr($headerstring, $VBRidOffset, strlen('Info')) == 'Xing') {
627					$thisfile_mpeg_audio['bitrate_mode'] = 'vbr';
628					$thisfile_mpeg_audio['VBR_method']   = 'Xing';
629//				} else {
630//					$ScanAsCBR = true;
631//					$thisfile_mpeg_audio['bitrate_mode'] = 'cbr';
632//				}
633
634				$thisfile_mpeg_audio['xing_flags_raw'] = getid3_lib::BigEndian2Int(substr($headerstring, $VBRidOffset + 4, 4));
635
636				$thisfile_mpeg_audio['xing_flags']['frames']    = (bool) ($thisfile_mpeg_audio['xing_flags_raw'] & 0x00000001);
637				$thisfile_mpeg_audio['xing_flags']['bytes']     = (bool) ($thisfile_mpeg_audio['xing_flags_raw'] & 0x00000002);
638				$thisfile_mpeg_audio['xing_flags']['toc']       = (bool) ($thisfile_mpeg_audio['xing_flags_raw'] & 0x00000004);
639				$thisfile_mpeg_audio['xing_flags']['vbr_scale'] = (bool) ($thisfile_mpeg_audio['xing_flags_raw'] & 0x00000008);
640
641				if ($thisfile_mpeg_audio['xing_flags']['frames']) {
642					$thisfile_mpeg_audio['VBR_frames'] = getid3_lib::BigEndian2Int(substr($headerstring, $VBRidOffset +  8, 4));
643					//$thisfile_mpeg_audio['VBR_frames']--; // don't count header Xing/Info frame
644				}
645				if ($thisfile_mpeg_audio['xing_flags']['bytes']) {
646					$thisfile_mpeg_audio['VBR_bytes']  = getid3_lib::BigEndian2Int(substr($headerstring, $VBRidOffset + 12, 4));
647				}
648
649				//if (($thisfile_mpeg_audio['bitrate'] == 'free') && !empty($thisfile_mpeg_audio['VBR_frames']) && !empty($thisfile_mpeg_audio['VBR_bytes'])) {
650				if (!empty($thisfile_mpeg_audio['VBR_frames']) && !empty($thisfile_mpeg_audio['VBR_bytes'])) {
651
652					$framelengthfloat = $thisfile_mpeg_audio['VBR_bytes'] / $thisfile_mpeg_audio['VBR_frames'];
653
654					if ($thisfile_mpeg_audio['layer'] == '1') {
655						// BitRate = (((FrameLengthInBytes / 4) - Padding) * SampleRate) / 12
656						//$info['audio']['bitrate'] = ((($framelengthfloat / 4) - intval($thisfile_mpeg_audio['padding'])) * $thisfile_mpeg_audio['sample_rate']) / 12;
657						$info['audio']['bitrate'] = ($framelengthfloat / 4) * $thisfile_mpeg_audio['sample_rate'] * (2 / $info['audio']['channels']) / 12;
658					} else {
659						// Bitrate = ((FrameLengthInBytes - Padding) * SampleRate) / 144
660						//$info['audio']['bitrate'] = (($framelengthfloat - intval($thisfile_mpeg_audio['padding'])) * $thisfile_mpeg_audio['sample_rate']) / 144;
661						$info['audio']['bitrate'] = $framelengthfloat * $thisfile_mpeg_audio['sample_rate'] * (2 / $info['audio']['channels']) / 144;
662					}
663					$thisfile_mpeg_audio['framelength'] = floor($framelengthfloat);
664				}
665
666				if ($thisfile_mpeg_audio['xing_flags']['toc']) {
667					$LAMEtocData = substr($headerstring, $VBRidOffset + 16, 100);
668					for ($i = 0; $i < 100; $i++) {
669						$thisfile_mpeg_audio['toc'][$i] = ord($LAMEtocData{$i});
670					}
671				}
672				if ($thisfile_mpeg_audio['xing_flags']['vbr_scale']) {
673					$thisfile_mpeg_audio['VBR_scale'] = getid3_lib::BigEndian2Int(substr($headerstring, $VBRidOffset + 116, 4));
674				}
675
676
677				// http://gabriel.mp3-tech.org/mp3infotag.html
678				if (substr($headerstring, $VBRidOffset + 120, 4) == 'LAME') {
679
680					// shortcut
681					$thisfile_mpeg_audio['LAME'] = array();
682					$thisfile_mpeg_audio_lame    = &$thisfile_mpeg_audio['LAME'];
683
684
685					$thisfile_mpeg_audio_lame['long_version']  = substr($headerstring, $VBRidOffset + 120, 20);
686					$thisfile_mpeg_audio_lame['short_version'] = substr($thisfile_mpeg_audio_lame['long_version'], 0, 9);
687
688					if ($thisfile_mpeg_audio_lame['short_version'] >= 'LAME3.90') {
689
690						// extra 11 chars are not part of version string when LAMEtag present
691						unset($thisfile_mpeg_audio_lame['long_version']);
692
693						// It the LAME tag was only introduced in LAME v3.90
694						// http://www.hydrogenaudio.org/?act=ST&f=15&t=9933
695
696						// Offsets of various bytes in http://gabriel.mp3-tech.org/mp3infotag.html
697						// are assuming a 'Xing' identifier offset of 0x24, which is the case for
698						// MPEG-1 non-mono, but not for other combinations
699						$LAMEtagOffsetContant = $VBRidOffset - 0x24;
700
701						// shortcuts
702						$thisfile_mpeg_audio_lame['RGAD']    = array('track'=>array(), 'album'=>array());
703						$thisfile_mpeg_audio_lame_RGAD       = &$thisfile_mpeg_audio_lame['RGAD'];
704						$thisfile_mpeg_audio_lame_RGAD_track = &$thisfile_mpeg_audio_lame_RGAD['track'];
705						$thisfile_mpeg_audio_lame_RGAD_album = &$thisfile_mpeg_audio_lame_RGAD['album'];
706						$thisfile_mpeg_audio_lame['raw'] = array();
707						$thisfile_mpeg_audio_lame_raw    = &$thisfile_mpeg_audio_lame['raw'];
708
709						// byte $9B  VBR Quality
710						// This field is there to indicate a quality level, although the scale was not precised in the original Xing specifications.
711						// Actually overwrites original Xing bytes
712						unset($thisfile_mpeg_audio['VBR_scale']);
713						$thisfile_mpeg_audio_lame['vbr_quality'] = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0x9B, 1));
714
715						// bytes $9C-$A4  Encoder short VersionString
716						$thisfile_mpeg_audio_lame['short_version'] = substr($headerstring, $LAMEtagOffsetContant + 0x9C, 9);
717
718						// byte $A5  Info Tag revision + VBR method
719						$LAMEtagRevisionVBRmethod = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xA5, 1));
720
721						$thisfile_mpeg_audio_lame['tag_revision']   = ($LAMEtagRevisionVBRmethod & 0xF0) >> 4;
722						$thisfile_mpeg_audio_lame_raw['vbr_method'] =  $LAMEtagRevisionVBRmethod & 0x0F;
723						$thisfile_mpeg_audio_lame['vbr_method']     = getid3_mp3::LAMEvbrMethodLookup($thisfile_mpeg_audio_lame_raw['vbr_method']);
724						$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'
725
726						// byte $A6  Lowpass filter value
727						$thisfile_mpeg_audio_lame['lowpass_frequency'] = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xA6, 1)) * 100;
728
729						// bytes $A7-$AE  Replay Gain
730						// http://privatewww.essex.ac.uk/~djmrob/replaygain/rg_data_format.html
731						// bytes $A7-$AA : 32 bit floating point "Peak signal amplitude"
732						if ($thisfile_mpeg_audio_lame['short_version'] >= 'LAME3.94b') {
733							// LAME 3.94a16 and later - 9.23 fixed point
734							// ie 0x0059E2EE / (2^23) = 5890798 / 8388608 = 0.7022378444671630859375
735							$thisfile_mpeg_audio_lame_RGAD['peak_amplitude'] = (float) ((getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xA7, 4))) / 8388608);
736						} else {
737							// LAME 3.94a15 and earlier - 32-bit floating point
738							// Actually 3.94a16 will fall in here too and be WRONG, but is hard to detect 3.94a16 vs 3.94a15
739							$thisfile_mpeg_audio_lame_RGAD['peak_amplitude'] = getid3_lib::LittleEndian2Float(substr($headerstring, $LAMEtagOffsetContant + 0xA7, 4));
740						}
741						if ($thisfile_mpeg_audio_lame_RGAD['peak_amplitude'] == 0) {
742							unset($thisfile_mpeg_audio_lame_RGAD['peak_amplitude']);
743						} else {
744							$thisfile_mpeg_audio_lame_RGAD['peak_db'] = getid3_lib::RGADamplitude2dB($thisfile_mpeg_audio_lame_RGAD['peak_amplitude']);
745						}
746
747						$thisfile_mpeg_audio_lame_raw['RGAD_track']      =   getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xAB, 2));
748						$thisfile_mpeg_audio_lame_raw['RGAD_album']      =   getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xAD, 2));
749
750
751						if ($thisfile_mpeg_audio_lame_raw['RGAD_track'] != 0) {
752
753							$thisfile_mpeg_audio_lame_RGAD_track['raw']['name']        = ($thisfile_mpeg_audio_lame_raw['RGAD_track'] & 0xE000) >> 13;
754							$thisfile_mpeg_audio_lame_RGAD_track['raw']['originator']  = ($thisfile_mpeg_audio_lame_raw['RGAD_track'] & 0x1C00) >> 10;
755							$thisfile_mpeg_audio_lame_RGAD_track['raw']['sign_bit']    = ($thisfile_mpeg_audio_lame_raw['RGAD_track'] & 0x0200) >> 9;
756							$thisfile_mpeg_audio_lame_RGAD_track['raw']['gain_adjust'] =  $thisfile_mpeg_audio_lame_raw['RGAD_track'] & 0x01FF;
757							$thisfile_mpeg_audio_lame_RGAD_track['name']       = getid3_lib::RGADnameLookup($thisfile_mpeg_audio_lame_RGAD_track['raw']['name']);
758							$thisfile_mpeg_audio_lame_RGAD_track['originator'] = getid3_lib::RGADoriginatorLookup($thisfile_mpeg_audio_lame_RGAD_track['raw']['originator']);
759							$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']);
760
761							if (!empty($thisfile_mpeg_audio_lame_RGAD['peak_amplitude'])) {
762								$info['replay_gain']['track']['peak']   = $thisfile_mpeg_audio_lame_RGAD['peak_amplitude'];
763							}
764							$info['replay_gain']['track']['originator'] = $thisfile_mpeg_audio_lame_RGAD_track['originator'];
765							$info['replay_gain']['track']['adjustment'] = $thisfile_mpeg_audio_lame_RGAD_track['gain_db'];
766						} else {
767							unset($thisfile_mpeg_audio_lame_RGAD['track']);
768						}
769						if ($thisfile_mpeg_audio_lame_raw['RGAD_album'] != 0) {
770
771							$thisfile_mpeg_audio_lame_RGAD_album['raw']['name']        = ($thisfile_mpeg_audio_lame_raw['RGAD_album'] & 0xE000) >> 13;
772							$thisfile_mpeg_audio_lame_RGAD_album['raw']['originator']  = ($thisfile_mpeg_audio_lame_raw['RGAD_album'] & 0x1C00) >> 10;
773							$thisfile_mpeg_audio_lame_RGAD_album['raw']['sign_bit']    = ($thisfile_mpeg_audio_lame_raw['RGAD_album'] & 0x0200) >> 9;
774							$thisfile_mpeg_audio_lame_RGAD_album['raw']['gain_adjust'] = $thisfile_mpeg_audio_lame_raw['RGAD_album'] & 0x01FF;
775							$thisfile_mpeg_audio_lame_RGAD_album['name']       = getid3_lib::RGADnameLookup($thisfile_mpeg_audio_lame_RGAD_album['raw']['name']);
776							$thisfile_mpeg_audio_lame_RGAD_album['originator'] = getid3_lib::RGADoriginatorLookup($thisfile_mpeg_audio_lame_RGAD_album['raw']['originator']);
777							$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']);
778
779							if (!empty($thisfile_mpeg_audio_lame_RGAD['peak_amplitude'])) {
780								$info['replay_gain']['album']['peak']   = $thisfile_mpeg_audio_lame_RGAD['peak_amplitude'];
781							}
782							$info['replay_gain']['album']['originator'] = $thisfile_mpeg_audio_lame_RGAD_album['originator'];
783							$info['replay_gain']['album']['adjustment'] = $thisfile_mpeg_audio_lame_RGAD_album['gain_db'];
784						} else {
785							unset($thisfile_mpeg_audio_lame_RGAD['album']);
786						}
787						if (empty($thisfile_mpeg_audio_lame_RGAD)) {
788							unset($thisfile_mpeg_audio_lame['RGAD']);
789						}
790
791
792						// byte $AF  Encoding flags + ATH Type
793						$EncodingFlagsATHtype = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xAF, 1));
794						$thisfile_mpeg_audio_lame['encoding_flags']['nspsytune']   = (bool) ($EncodingFlagsATHtype & 0x10);
795						$thisfile_mpeg_audio_lame['encoding_flags']['nssafejoint'] = (bool) ($EncodingFlagsATHtype & 0x20);
796						$thisfile_mpeg_audio_lame['encoding_flags']['nogap_next']  = (bool) ($EncodingFlagsATHtype & 0x40);
797						$thisfile_mpeg_audio_lame['encoding_flags']['nogap_prev']  = (bool) ($EncodingFlagsATHtype & 0x80);
798						$thisfile_mpeg_audio_lame['ath_type']                      =         $EncodingFlagsATHtype & 0x0F;
799
800						// byte $B0  if ABR {specified bitrate} else {minimal bitrate}
801						$thisfile_mpeg_audio_lame['raw']['abrbitrate_minbitrate'] = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB0, 1));
802						if ($thisfile_mpeg_audio_lame_raw['vbr_method'] == 2) { // Average BitRate (ABR)
803							$thisfile_mpeg_audio_lame['bitrate_abr'] = $thisfile_mpeg_audio_lame['raw']['abrbitrate_minbitrate'];
804						} elseif ($thisfile_mpeg_audio_lame_raw['vbr_method'] == 1) { // Constant BitRate (CBR)
805							// ignore
806						} elseif ($thisfile_mpeg_audio_lame['raw']['abrbitrate_minbitrate'] > 0) { // Variable BitRate (VBR) - minimum bitrate
807							$thisfile_mpeg_audio_lame['bitrate_min'] = $thisfile_mpeg_audio_lame['raw']['abrbitrate_minbitrate'];
808						}
809
810						// bytes $B1-$B3  Encoder delays
811						$EncoderDelays = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB1, 3));
812						$thisfile_mpeg_audio_lame['encoder_delay'] = ($EncoderDelays & 0xFFF000) >> 12;
813						$thisfile_mpeg_audio_lame['end_padding']   =  $EncoderDelays & 0x000FFF;
814
815						// byte $B4  Misc
816						$MiscByte = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB4, 1));
817						$thisfile_mpeg_audio_lame_raw['noise_shaping']       = ($MiscByte & 0x03);
818						$thisfile_mpeg_audio_lame_raw['stereo_mode']         = ($MiscByte & 0x1C) >> 2;
819						$thisfile_mpeg_audio_lame_raw['not_optimal_quality'] = ($MiscByte & 0x20) >> 5;
820						$thisfile_mpeg_audio_lame_raw['source_sample_freq']  = ($MiscByte & 0xC0) >> 6;
821						$thisfile_mpeg_audio_lame['noise_shaping']       = $thisfile_mpeg_audio_lame_raw['noise_shaping'];
822						$thisfile_mpeg_audio_lame['stereo_mode']         = getid3_mp3::LAMEmiscStereoModeLookup($thisfile_mpeg_audio_lame_raw['stereo_mode']);
823						$thisfile_mpeg_audio_lame['not_optimal_quality'] = (bool) $thisfile_mpeg_audio_lame_raw['not_optimal_quality'];
824						$thisfile_mpeg_audio_lame['source_sample_freq']  = getid3_mp3::LAMEmiscSourceSampleFrequencyLookup($thisfile_mpeg_audio_lame_raw['source_sample_freq']);
825
826						// byte $B5  MP3 Gain
827						$thisfile_mpeg_audio_lame_raw['mp3_gain'] = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB5, 1), false, true);
828						$thisfile_mpeg_audio_lame['mp3_gain_db']     = (getid3_lib::RGADamplitude2dB(2) / 4) * $thisfile_mpeg_audio_lame_raw['mp3_gain'];
829						$thisfile_mpeg_audio_lame['mp3_gain_factor'] = pow(2, ($thisfile_mpeg_audio_lame['mp3_gain_db'] / 6));
830
831						// bytes $B6-$B7  Preset and surround info
832						$PresetSurroundBytes = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB6, 2));
833						// Reserved                                                    = ($PresetSurroundBytes & 0xC000);
834						$thisfile_mpeg_audio_lame_raw['surround_info'] = ($PresetSurroundBytes & 0x3800);
835						$thisfile_mpeg_audio_lame['surround_info']     = getid3_mp3::LAMEsurroundInfoLookup($thisfile_mpeg_audio_lame_raw['surround_info']);
836						$thisfile_mpeg_audio_lame['preset_used_id']    = ($PresetSurroundBytes & 0x07FF);
837						$thisfile_mpeg_audio_lame['preset_used']       = getid3_mp3::LAMEpresetUsedLookup($thisfile_mpeg_audio_lame);
838						if (!empty($thisfile_mpeg_audio_lame['preset_used_id']) && empty($thisfile_mpeg_audio_lame['preset_used'])) {
839							$info['warning'][] = 'Unknown LAME preset used ('.$thisfile_mpeg_audio_lame['preset_used_id'].') - please report to info@getid3.org';
840						}
841						if (($thisfile_mpeg_audio_lame['short_version'] == 'LAME3.90.') && !empty($thisfile_mpeg_audio_lame['preset_used_id'])) {
842							// this may change if 3.90.4 ever comes out
843							$thisfile_mpeg_audio_lame['short_version'] = 'LAME3.90.3';
844						}
845
846						// bytes $B8-$BB  MusicLength
847						$thisfile_mpeg_audio_lame['audio_bytes'] = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB8, 4));
848						$ExpectedNumberOfAudioBytes = (($thisfile_mpeg_audio_lame['audio_bytes'] > 0) ? $thisfile_mpeg_audio_lame['audio_bytes'] : $thisfile_mpeg_audio['VBR_bytes']);
849
850						// bytes $BC-$BD  MusicCRC
851						$thisfile_mpeg_audio_lame['music_crc']    = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xBC, 2));
852
853						// bytes $BE-$BF  CRC-16 of Info Tag
854						$thisfile_mpeg_audio_lame['lame_tag_crc'] = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xBE, 2));
855
856
857						// LAME CBR
858						if ($thisfile_mpeg_audio_lame_raw['vbr_method'] == 1) {
859
860							$thisfile_mpeg_audio['bitrate_mode'] = 'cbr';
861							$thisfile_mpeg_audio['bitrate'] = getid3_mp3::ClosestStandardMP3Bitrate($thisfile_mpeg_audio['bitrate']);
862							$info['audio']['bitrate'] = $thisfile_mpeg_audio['bitrate'];
863							//if (empty($thisfile_mpeg_audio['bitrate']) || (!empty($thisfile_mpeg_audio_lame['bitrate_min']) && ($thisfile_mpeg_audio_lame['bitrate_min'] != 255))) {
864							//	$thisfile_mpeg_audio['bitrate'] = $thisfile_mpeg_audio_lame['bitrate_min'];
865							//}
866
867						}
868
869					}
870				}
871
872			} else {
873
874				// not Fraunhofer or Xing VBR methods, most likely CBR (but could be VBR with no header)
875				$thisfile_mpeg_audio['bitrate_mode'] = 'cbr';
876				if ($recursivesearch) {
877					$thisfile_mpeg_audio['bitrate_mode'] = 'vbr';
878					if ($this->RecursiveFrameScanning($offset, $nextframetestoffset, true)) {
879						$recursivesearch = false;
880						$thisfile_mpeg_audio['bitrate_mode'] = 'cbr';
881					}
882					if ($thisfile_mpeg_audio['bitrate_mode'] == 'vbr') {
883						$info['warning'][] = 'VBR file with no VBR header. Bitrate values calculated from actual frame bitrates.';
884					}
885				}
886
887			}
888
889		}
890
891		if (($ExpectedNumberOfAudioBytes > 0) && ($ExpectedNumberOfAudioBytes != ($info['avdataend'] - $info['avdataoffset']))) {
892			if ($ExpectedNumberOfAudioBytes > ($info['avdataend'] - $info['avdataoffset'])) {
893				if (isset($info['fileformat']) && ($info['fileformat'] == 'riff')) {
894					// ignore, audio data is broken into chunks so will always be data "missing"
895				} elseif (($ExpectedNumberOfAudioBytes - ($info['avdataend'] - $info['avdataoffset'])) == 1) {
896					$info['warning'][] = 'Last byte of data truncated (this is a known bug in Meracl ID3 Tag Writer before v1.3.5)';
897				} else {
898					$info['warning'][] = 'Probable truncated file: expecting '.$ExpectedNumberOfAudioBytes.' bytes of audio data, only found '.($info['avdataend'] - $info['avdataoffset']).' (short by '.($ExpectedNumberOfAudioBytes - ($info['avdat…

Large files files are truncated, but you can click here to view the full file