///////////////////////////////////////////////////////////////// /// getID3() by James Heinrich <info@getid3.org> // // available at https://github.com/JamesHeinrich/getID3 // // or https://www.getid3.org // // or http://getid3.sourceforge.net // // see readme.txt for more details // ///////////////////////////////////////////////////////////////// // // // module.audio.mp3.php // // module for analyzing MP3 files // // dependencies: NONE // // /// /////////////////////////////////////////////////////////////////
if (!defined('GETID3_INCLUDEPATH')) { // prevent path-exposing attacks that access modules directly on public webservers exit; }
class getid3_mp3 extends getid3_handler { /** * 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-unusable files. * * @var bool */ public $allow_bruteforce = false;
/** * number of frames to scan to determine if MPEG-audio sequence is valid * Lower this number to 5-20 for faster scanning * Increase this number to 50+ for most accurate detection of valid VBR/CBR mpeg-audio streams * * @var int */ public $mp3_valid_check_frames = 50;
/** * @return bool */ public function Analyze() { $info = &$this->getid3->info;
$initialOffset = $info['avdataoffset'];
if (!$this->getOnlyMPEGaudioInfo($info['avdataoffset'])) { if ($this->allow_bruteforce) { $this->error('Rescanning file in BruteForce mode'); $this->getOnlyMPEGaudioInfoBruteForce(); } }
if (isset($info['mpeg']['audio']['bitrate_mode'])) { $info['audio']['bitrate_mode'] = strtolower($info['mpeg']['audio']['bitrate_mode']); }
$synchoffsetwarning = 'Unknown data before synch '; if (isset($info['id3v2']['headerlength'])) { $synchoffsetwarning .= '(ID3v2 header ends at '.$info['id3v2']['headerlength'].', then '.($info['avdataoffset'] - $info['id3v2']['headerlength']).' bytes garbage, '; } elseif ($initialOffset > 0) { $synchoffsetwarning .= '(should be at '.$initialOffset.', '; } else { $synchoffsetwarning .= '(should be at beginning of file, '; } $synchoffsetwarning .= 'synch detected at '.$info['avdataoffset'].')'; if (isset($info['audio']['bitrate_mode']) && ($info['audio']['bitrate_mode'] == 'cbr')) {
if (!empty($info['id3v2']['headerlength']) && (($info['avdataoffset'] - $info['id3v2']['headerlength']) == $info['mpeg']['audio']['framelength'])) {
$synchoffsetwarning .= '. This is a known problem with some versions of LAME (3.90-3.92) DLL in CBR mode.'; $info['audio']['codec'] = 'LAME'; $CurrentDataLAMEversionString = 'LAME3.';
$synchoffsetwarning .= '. This is a known problem with some versions of LAME (3.90 - 3.92) DLL in CBR mode.'; $info['audio']['codec'] = 'LAME'; $CurrentDataLAMEversionString = 'LAME3.';
$CurrentDataLAMEversionString = (!empty($CurrentDataLAMEversionString) ? $CurrentDataLAMEversionString : (isset($info['audio']['encoder']) ? $info['audio']['encoder'] : '')); if (!empty($CurrentDataLAMEversionString) && (substr($CurrentDataLAMEversionString, 0, 6) == 'LAME3.') && !preg_match('[0-9\)]', substr($CurrentDataLAMEversionString, -1))) { // a version number of LAME that does not end with a number like "LAME3.92" // or with a closing parenthesis like "LAME3.88 (alpha)" // or a version of LAME with the LAMEtag-not-filled-in-DLL-mode bug (3.90-3.92)
// not sure what the actual last frame length will be, but will be less than or equal to 1441 $PossiblyLongerLAMEversion_FrameLength = 1441;
// Not sure what version of LAME this is - look in padding of last frame for longer version string $PossibleLAMEversionStringOffset = $info['avdataend'] - $PossiblyLongerLAMEversion_FrameLength; $this->fseek($PossibleLAMEversionStringOffset); $PossiblyLongerLAMEversion_Data = $this->fread($PossiblyLongerLAMEversion_FrameLength); switch (substr($CurrentDataLAMEversionString, -1)) { case 'a': case 'b': // "LAME3.94a" will have a longer version string of "LAME3.94 (alpha)" for example // need to trim off "a" to match longer string $CurrentDataLAMEversionString = substr($CurrentDataLAMEversionString, 0, -1); break; } if (($PossiblyLongerLAMEversion_String = strstr($PossiblyLongerLAMEversion_Data, $CurrentDataLAMEversionString)) !== false) { if (substr($PossiblyLongerLAMEversion_String, 0, strlen($CurrentDataLAMEversionString)) == $CurrentDataLAMEversionString) { $PossiblyLongerLAMEversion_NewString = substr($PossiblyLongerLAMEversion_String, 0, strspn($PossiblyLongerLAMEversion_String, 'LAME0123456789., (abcdefghijklmnopqrstuvwxyzJFSOND)')); //"LAME3.90.3" "LAME3.87 (beta 1, Sep 27 2000)" "LAME3.88 (beta)" if (empty($info['audio']['encoder']) || (strlen($PossiblyLongerLAMEversion_NewString) > strlen($info['audio']['encoder']))) { if (!empty($info['audio']['encoder']) && !empty($info['mpeg']['audio']['LAME']['short_version']) && ($info['audio']['encoder'] == $info['mpeg']['audio']['LAME']['short_version'])) { if (preg_match('#^LAME[0-9\\.]+#', $PossiblyLongerLAMEversion_NewString, $matches)) { // "LAME3.100" -> "LAME3.100.1", but avoid including "(alpha)" and similar $info['mpeg']['audio']['LAME']['short_version'] = $matches[0]; } } $info['audio']['encoder'] = $PossiblyLongerLAMEversion_NewString; } } } } if (!empty($info['audio']['encoder'])) { $info['audio']['encoder'] = rtrim($info['audio']['encoder'], "\x00 "); }
switch (isset($info['mpeg']['audio']['layer']) ? $info['mpeg']['audio']['layer'] : '') { case 1: case 2: $info['audio']['dataformat'] = 'mp'.$info['mpeg']['audio']['layer']; break; } if (isset($info['fileformat']) && ($info['fileformat'] == 'mp3')) { switch ($info['audio']['dataformat']) { case 'mp1': case 'mp2': case 'mp3': $info['fileformat'] = $info['audio']['dataformat']; break;
default: $this->warning('Expecting [audio][dataformat] to be mp1/mp2/mp3 when fileformat == mp3, [audio][dataformat] actually "'.$info['audio']['dataformat'].'"'); break; } }
if (empty($info['fileformat'])) { unset($info['fileformat']); unset($info['audio']['bitrate_mode']); unset($info['avdataoffset']); unset($info['avdataend']); return false; }
// Calculate playtime if (!isset($info['playtime_seconds']) && isset($info['audio']['bitrate']) && ($info['audio']['bitrate'] > 0)) { // https://github.com/JamesHeinrich/getID3/issues/161 // VBR header frame contains ~0.026s of silent audio data, but is not actually part of the original encoding and should be ignored $xingVBRheaderFrameLength = ((isset($info['mpeg']['audio']['VBR_frames']) && isset($info['mpeg']['audio']['framelength'])) ? $info['mpeg']['audio']['framelength'] : 0);
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']])) {
if (!empty($thisfile_mpeg_audio_lame['encoding_flags']['nogap_prev']) || !empty($thisfile_mpeg_audio_lame['encoding_flags']['nogap_next'])) { $encoder_options .= ' --nogap'; }
if (!empty($thisfile_mpeg_audio_lame['lowpass_frequency'])) { $ExplodedOptions = explode(' ', $encoder_options, 4); if ($ExplodedOptions[0] == '--r3mix') { $ExplodedOptions[1] = 'r3mix'; } switch ($ExplodedOptions[0]) { case '--preset': case '--alt-preset': case '--r3mix': if ($ExplodedOptions[1] == 'fast') { $ExplodedOptions[1] .= ' '.$ExplodedOptions[2]; } switch ($ExplodedOptions[1]) { case 'portable': case 'medium': case 'standard': case 'extreme': case 'insane': case 'fast portable': case 'fast medium': case 'fast standard': case 'fast extreme': case 'fast insane': case 'r3mix': static $ExpectedLowpass = array( 'insane|20500' => 20500, 'insane|20600' => 20600, // 3.90.2, 3.90.3, 3.91 'medium|18000' => 18000, 'fast medium|18000' => 18000, 'extreme|19500' => 19500, // 3.90, 3.90.1, 3.92, 3.95 'extreme|19600' => 19600, // 3.90.2, 3.90.3, 3.91, 3.93.1 'fast extreme|19500' => 19500, // 3.90, 3.90.1, 3.92, 3.95 'fast extreme|19600' => 19600, // 3.90.2, 3.90.3, 3.91, 3.93.1 'standard|19000' => 19000, 'fast standard|19000' => 19000, 'r3mix|19500' => 19500, // 3.90, 3.90.1, 3.92 'r3mix|19600' => 19600, // 3.90.2, 3.90.3, 3.91 'r3mix|18000' => 18000, // 3.94, 3.95 ); 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))) { $encoder_options .= ' --lowpass '.$thisfile_mpeg_audio_lame['lowpass_frequency']; } break;
default: break; } break; } }
if (isset($thisfile_mpeg_audio_lame['raw']['source_sample_freq'])) { if (($thisfile_mpeg_audio['sample_rate'] == 44100) && ($thisfile_mpeg_audio_lame['raw']['source_sample_freq'] != 1)) { $encoder_options .= ' --resample 44100'; } elseif (($thisfile_mpeg_audio['sample_rate'] == 48000) && ($thisfile_mpeg_audio_lame['raw']['source_sample_freq'] != 2)) { $encoder_options .= ' --resample 48000'; } elseif ($thisfile_mpeg_audio['sample_rate'] < 44100) { switch ($thisfile_mpeg_audio_lame['raw']['source_sample_freq']) { case 0: // <= 32000 // may or may not be same as source frequency - ignore break; case 1: // 44100 case 2: // 48000 case 3: // 48000+ $ExplodedOptions = explode(' ', $encoder_options, 4); switch ($ExplodedOptions[0]) { case '--preset': case '--alt-preset': switch ($ExplodedOptions[1]) { case 'fast': case 'portable': case 'medium': case 'standard': case 'extreme': case 'insane': $encoder_options .= ' --resample '.$thisfile_mpeg_audio['sample_rate']; break;
if ($this->fseek($offset) != 0) { $this->error('decodeMPEGaudioHeader() failed to seek to next offset at '.$offset); return false; } //$headerstring = $this->fread(1441); // worst-case max length = 32kHz @ 320kbps layer 3 = 1441 bytes/frame $headerstring = $this->fread(226); // LAME header at offset 36 + 190 bytes of Xing/LAME data
// MP3 audio frame structure: // $aa $aa $aa $aa [$bb $bb] $cc... // where $aa..$aa is the four-byte mpeg-audio header (below) // $bb $bb is the optional 2-byte CRC // and $cc... is the audio data
if ($thisfile_mpeg_audio['protection']) { $thisfile_mpeg_audio['crc'] = getid3_lib::BigEndian2Int(substr($headerstring, 4, 2)); } }
if ($thisfile_mpeg_audio['raw']['bitrate'] == 15) { // http://www.hydrogenaudio.org/?act=ST&f=16&t=9682&st=0 $this->warning('Invalid bitrate index (15), this is a known bug in free-format MP3s encoded by LAME v3.90 - 3.93.1'); $thisfile_mpeg_audio['raw']['bitrate'] = 0; } $thisfile_mpeg_audio['padding'] = (bool) $thisfile_mpeg_audio['raw']['padding']; $thisfile_mpeg_audio['bitrate'] = $MPEGaudioBitrateLookup[$thisfile_mpeg_audio['version']][$thisfile_mpeg_audio['layer']][$thisfile_mpeg_audio['raw']['bitrate']];
if (($thisfile_mpeg_audio['bitrate'] == 'free') && ($offset == $info['avdataoffset'])) { // only skip multiple frame check if free-format bitstream found at beginning of file // otherwise is quite possibly simply corrupted data $recursivesearch = false; }
// For Layer 2 there are some combinations of bitrate and mode which are not allowed. if (!$FastMPEGheaderScan && ($thisfile_mpeg_audio['layer'] == '2')) {
case 'mono': if (($thisfile_mpeg_audio['bitrate'] == 'free') || ($thisfile_mpeg_audio['bitrate'] <= 192000)) { // these are ok } else { $this->error($thisfile_mpeg_audio['bitrate'].'kbps not allowed in Layer 2, '.$thisfile_mpeg_audio['channelmode'].'.'); return false; } break;
case 'stereo': case 'joint stereo': case 'dual channel': if (($thisfile_mpeg_audio['bitrate'] == 'free') || ($thisfile_mpeg_audio['bitrate'] == 64000) || ($thisfile_mpeg_audio['bitrate'] >= 96000)) { // these are ok } else { $this->error(intval(round($thisfile_mpeg_audio['bitrate'] / 1000)).'kbps not allowed in Layer 2, '.$thisfile_mpeg_audio['channelmode'].'.'); return false; } break;
if (isset($thisfile_mpeg_audio['framelength'])) { $nextframetestoffset = $offset + $thisfile_mpeg_audio['framelength']; } else { $this->error('Frame at offset('.$offset.') is has an invalid frame length.'); return false; }
if (substr($headerstring, 4 + 32, 4) == 'VBRI') { // Fraunhofer VBR header is hardcoded 'VBRI' at offset 0x24 (36) // specs taken from http://minnie.tuhs.org/pipermail/mp3encoder/2001-January/001800.html
if ((substr($headerstring, $VBRidOffset, strlen('Xing')) == 'Xing') || (substr($headerstring, $VBRidOffset, strlen('Info')) == 'Info')) { // 'Xing' is traditional Xing VBR frame // 'Info' is LAME-encoded CBR (This was done to avoid CBR files to be recognized as traditional Xing VBR files by some decoders.) // 'Info' *can* legally be used to specify a VBR file as well, however.
// http://www.multiweb.cz/twoinches/MP3inside.htm //00..03 = "Xing" or "Info" //04..07 = Flags: // 0x01 Frames Flag set if value for number of frames in file is stored // 0x02 Bytes Flag set if value for filesize in bytes is stored // 0x04 TOC Flag set if values for TOC are stored // 0x08 VBR Scale Flag set if values for VBR scale is stored //08..11 Frames: Number of frames in file (including the first Xing/Info one) //12..15 Bytes: File length in Bytes //16..115 TOC (Table of Contents): // Contains of 100 indexes (one Byte length) for easier lookup in file. Approximately solves problem with moving inside file. // Each Byte has a value according this formula: // (TOC[i] / 256) * fileLenInBytes // 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: // TOC[(60/240)*100] = TOC[25] // and corresponding Byte in file is then approximately at: // (TOC[25]/256) * 5000000 //116..119 VBR Scale
// should be safe to leave this at 'vbr' and let it be overriden to 'cbr' if a CBR preset/mode is used by LAME // if (substr($headerstring, $VBRidOffset, strlen('Info')) == 'Xing') { $thisfile_mpeg_audio['bitrate_mode'] = 'vbr'; $thisfile_mpeg_audio['VBR_method'] = 'Xing'; // } else { // $ScanAsCBR = true; // $thisfile_mpeg_audio['bitrate_mode'] = 'cbr'; // }
//$thisfile_mpeg_audio_lame['numeric_version'] = str_replace('LAME', '', $thisfile_mpeg_audio_lame['short_version']); $thisfile_mpeg_audio_lame['numeric_version'] = ''; if (preg_match('#^LAME([0-9\\.a-z]*)#', $thisfile_mpeg_audio_lame['long_version'], $matches)) { $thisfile_mpeg_audio_lame['short_version'] = $matches[0]; $thisfile_mpeg_audio_lame['numeric_version'] = $matches[1]; } if (strlen($thisfile_mpeg_audio_lame['numeric_version']) > 0) { foreach (explode('.', $thisfile_mpeg_audio_lame['numeric_version']) as $key => $number) { $thisfile_mpeg_audio_lame['integer_version'][$key] = intval($number); } //if ($thisfile_mpeg_audio_lame['short_version'] >= 'LAME3.90') { if ((($thisfile_mpeg_audio_lame['integer_version'][0] * 1000) + $thisfile_mpeg_audio_lame['integer_version'][1]) >= 3090) { // cannot use string version compare, may have "LAME3.90" or "LAME3.100" -- see https://github.com/JamesHeinrich/getID3/issues/207
// extra 11 chars are not part of version string when LAMEtag present unset($thisfile_mpeg_audio_lame['long_version']);
// It the LAME tag was only introduced in LAME v3.90 // https://wiki.hydrogenaud.io/index.php/LAME#VBR_header_and_LAME_tag // https://hydrogenaud.io/index.php?topic=9933
// Offsets of various bytes in http://gabriel.mp3-tech.org/mp3infotag.html // are assuming a 'Xing' identifier offset of 0x24, which is the case for // MPEG-1 non-mono, but not for other combinations $LAMEtagOffsetContant = $VBRidOffset - 0x24;
// byte $9B VBR Quality // This field is there to indicate a quality level, although the scale was not precised in the original Xing specifications. // Actually overwrites original Xing bytes unset($thisfile_mpeg_audio['VBR_scale']); $thisfile_mpeg_audio_lame['vbr_quality'] = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0x9B, 1));
// bytes $A7-$AE Replay Gain // https://web.archive.org/web/20021015212753/http://privatewww.essex.ac.uk/~djmrob/replaygain/rg_data_format.html // bytes $A7-$AA : 32 bit floating point "Peak signal amplitude" if ($thisfile_mpeg_audio_lame['short_version'] >= 'LAME3.94b') { // LAME 3.94a16 and later - 9.23 fixed point // ie 0x0059E2EE / (2^23) = 5890798 / 8388608 = 0.7022378444671630859375 $thisfile_mpeg_audio_lame_RGAD['peak_amplitude'] = (float) ((getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xA7, 4))) / 8388608); } else { // LAME 3.94a15 and earlier - 32-bit floating point // Actually 3.94a16 will fall in here too and be WRONG, but is hard to detect 3.94a16 vs 3.94a15 $thisfile_mpeg_audio_lame_RGAD['peak_amplitude'] = getid3_lib::LittleEndian2Float(substr($headerstring, $LAMEtagOffsetContant + 0xA7, 4)); } if ($thisfile_mpeg_audio_lame_RGAD['peak_amplitude'] == 0) { unset($thisfile_mpeg_audio_lame_RGAD['peak_amplitude']); } else { $thisfile_mpeg_audio_lame_RGAD['peak_db'] = getid3_lib::RGADamplitude2dB($thisfile_mpeg_audio_lame_RGAD['peak_amplitude']); }
// bytes $BE-$BF CRC-16 of Info Tag $thisfile_mpeg_audio_lame['lame_tag_crc'] = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xBE, 2));
// not Fraunhofer or Xing VBR methods, most likely CBR (but could be VBR with no header) $thisfile_mpeg_audio['bitrate_mode'] = 'cbr'; if ($recursivesearch) { $thisfile_mpeg_audio['bitrate_mode'] = 'vbr'; if ($this->RecursiveFrameScanning($offset, $nextframetestoffset, true)) { $recursivesearch = false; $thisfile_mpeg_audio['bitrate_mode'] = 'cbr'; } if ($thisfile_mpeg_audio['bitrate_mode'] == 'vbr') { $this->warning('VBR file with no VBR header. Bitrate values calculated from actual frame bitrates.'); } }
}
}
if (($ExpectedNumberOfAudioBytes > 0) && ($ExpectedNumberOfAudioBytes != ($info['avdataend'] - $info['avdataoffset']))) { if ($ExpectedNumberOfAudioBytes > ($info['avdataend'] - $info['avdataoffset'])) { if ($this->isDependencyFor('matroska') || $this->isDependencyFor('riff')) { // ignore, audio data is broken into chunks so will always be data "missing" } elseif (($ExpectedNumberOfAudioBytes - ($info['avdataend'] - $info['avdataoffset'])) == 1) { $this->warning('Last byte of data truncated (this is a known bug in Meracl ID3 Tag Writer before v1.3.5)'); } else { $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)'); } } else { if ((($info['avdataend'] - $info['avdataoffset']) - $ExpectedNumberOfAudioBytes) == 1) { // $prenullbytefileoffset = $this->ftell(); // $this->fseek($info['avdataend']); // $PossibleNullByte = $this->fread(1); // $this->fseek($prenullbytefileoffset); // if ($PossibleNullByte === "\x00") { $info['avdataend']--; // $this->warning('Extra null byte at end of MP3 data assumed to be RIFF padding and therefore ignored'); // } else { // $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)'); // } } else { $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)'); } } }
$info['mp3_validity_check_bitrates'] = array(); for ($i = 0; $i < $this->mp3_valid_check_frames; $i++) { // check next (default: 50) frames for validity, to make sure we haven't run across a false synch if (($nextframetestoffset + 4) >= $info['avdataend']) { // end of file return true; }
$nextframetestarray = array('error' => array(), 'warning' => array(), 'avdataend' => $info['avdataend'], 'avdataoffset'=>$info['avdataoffset']); if ($this->decodeMPEGaudioHeader($nextframetestoffset, $nextframetestarray, false)) { /** @phpstan-ignore-next-line */ getid3_lib::safe_inc($info['mp3_validity_check_bitrates'][$nextframetestarray['mpeg']['audio']['bitrate']]); if ($ScanAsCBR) { // force CBR mode, used for trying to pick out invalid audio streams with valid(?) VBR headers, or VBR streams with no VBR header if (!isset($nextframetestarray['mpeg']['audio']['bitrate']) || !isset($firstframetestarray['mpeg']['audio']['bitrate']) || ($nextframetestarray['mpeg']['audio']['bitrate'] != $firstframetestarray['mpeg']['audio']['bitrate'])) { return false; } }
// next frame is OK, get ready to check the one after that if (isset($nextframetestarray['mpeg']['audio']['framelength']) && ($nextframetestarray['mpeg']['audio']['framelength'] > 0)) { $nextframetestoffset += $nextframetestarray['mpeg']['audio']['framelength']; } else { $this->error('Frame at offset ('.$offset.') is has an invalid frame length.'); return false; }
// 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 return true;
} else {
// next frame is not valid, note the error and fail, so scanning can contiue for a valid frame sequence $this->warning('Frame at offset ('.$offset.') is valid, but the next one at ('.$nextframetestoffset.') is not.');
return false; } } return true; }
/** * @param int $offset * @param bool $deepscan * * @return int|false */ public function FreeFormatFrameLength($offset, $deepscan=false) { $info = &$this->getid3->info;
$SyncPattern1 = substr($MPEGaudioData, 0, 4); // may be different pattern due to padding $SyncPattern2 = $SyncPattern1[0].$SyncPattern1[1].chr(ord($SyncPattern1[2]) | 0x02).$SyncPattern1[3]; if ($SyncPattern2 === $SyncPattern1) { $SyncPattern2 = $SyncPattern1[0].$SyncPattern1[1].chr(ord($SyncPattern1[2]) & 0xFD).$SyncPattern1[3]; }
// LAME 3.88 has a different value for modeextension on the first frame vs the rest $framelength1 = strpos($MPEGaudioData, substr($SyncPattern1, 0, 3), 4); $framelength2 = strpos($MPEGaudioData, substr($SyncPattern2, 0, 3), 4);
if ($framelength1 > 4) { $framelength = $framelength1; } if (($framelength2 > 4) && ($framelength2 < $framelength1)) { $framelength = $framelength2; } if (!$framelength) { $this->error('Cannot find next free-format synch pattern ('.getid3_lib::PrintHexBytes($SyncPattern1).' or '.getid3_lib::PrintHexBytes($SyncPattern2).') after offset '.$offset); return false; } else { $this->warning('ModeExtension varies between first frame and other frames (known free-format issue in LAME 3.88)'); $info['audio']['codec'] = 'LAME'; $info['audio']['encoder'] = 'LAME3.88'; $SyncPattern1 = substr($SyncPattern1, 0, 3); $SyncPattern2 = substr($SyncPattern2, 0, 3); } }
if ($deepscan) {
$ActualFrameLengthValues = array(); $nextoffset = $offset + $framelength; while ($nextoffset < ($info['avdataend'] - 6)) { $this->fseek($nextoffset - 1); $NextSyncPattern = $this->fread(6); if ((substr($NextSyncPattern, 1, strlen($SyncPattern1)) == $SyncPattern1) || (substr($NextSyncPattern, 1, strlen($SyncPattern2)) == $SyncPattern2)) { // good - found where expected $ActualFrameLengthValues[] = $framelength; } elseif ((substr($NextSyncPattern, 0, strlen($SyncPattern1)) == $SyncPattern1) || (substr($NextSyncPattern, 0, strlen($SyncPattern2)) == $SyncPattern2)) { // ok - found one byte earlier than expected (last frame wasn't padded, first frame was) $ActualFrameLengthValues[] = ($framelength - 1); $nextoffset--; } elseif ((substr($NextSyncPattern, 2, strlen($SyncPattern1)) == $SyncPattern1) || (substr($NextSyncPattern, 2, strlen($SyncPattern2)) == $SyncPattern2)) { // ok - found one byte later than expected (last frame was padded, first frame wasn't) $ActualFrameLengthValues[] = ($framelength + 1); $nextoffset++; } else { $this->error('Did not find expected free-format sync pattern at offset '.$nextoffset); return false; } $nextoffset += $framelength; } if (count($ActualFrameLengthValues) > 0) { $framelength = intval(round(array_sum($ActualFrameLengthValues) / count($ActualFrameLengthValues))); } } return $framelength; }
if ($SynchSeekOffset > $sync_seek_buffer_size) { // if a synch's not found within the first 128k bytes, then give up $this->error('Could not find valid MPEG audio synch within the first '.round($sync_seek_buffer_size / 1024).'kB'); if (isset($info['audio']['bitrate'])) { unset($info['audio']['bitrate']); } if (isset($info['mpeg']['audio'])) { unset($info['mpeg']['audio']); } if (empty($info['mpeg'])) { unset($info['mpeg']); } return false; } }
if (($SynchSeekOffset + 1) >= strlen($header)) { $this->error('Could not find valid MPEG synch before end of file'); return false; }
if (($header[$SynchSeekOffset] == "\xFF") && ($header[($SynchSeekOffset + 1)] > "\xE0")) { // possible synch detected if (++$SyncSeekAttempts >= $SyncSeekAttemptsMax) { // https://github.com/JamesHeinrich/getID3/issues/286 // corrupt files claiming to be MP3, with a large number of 0xFF bytes near the beginning, can cause this loop to take a very long time // should have escape condition to avoid spending too much time scanning a corrupt file // if a synch's not found within the first 128k bytes, then give up $this->error('Could not find valid MPEG audio synch after scanning '.$SyncSeekAttempts.' candidate offsets'); if (isset($info['audio']['bitrate'])) { unset($info['audio']['bitrate']); } if (isset($info['mpeg']['audio'])) { unset($info['mpeg']['audio']); } if (empty($info['mpeg'])) { unset($info['mpeg']); } return false; } $FirstFrameAVDataOffset = null; if (!isset($FirstFrameThisfileInfo) && !isset($info['mpeg']['audio'])) { $FirstFrameThisfileInfo = $info; $FirstFrameAVDataOffset = $avdataoffset + $SynchSeekOffset; if (!$this->decodeMPEGaudioHeader($FirstFrameAVDataOffset, $FirstFrameThisfileInfo, false)) { // if this is the first valid MPEG-audio frame, save it in case it's a VBR header frame and there's // garbage between this frame and a valid sequence of MPEG-audio frames, to be restored below unset($FirstFrameThisfileInfo); } }
$dummy = $info; // only overwrite real data if valid header found if ($this->decodeMPEGaudioHeader($avdataoffset + $SynchSeekOffset, $dummy, true)) { $info = $dummy; $info['avdataoffset'] = $avdataoffset + $SynchSeekOffset; switch (isset($info['fileformat']) ? $info['fileformat'] : '') { case '': case 'id3': case 'ape': case 'mp3': $info['fileformat'] = 'mp3'; $info['audio']['dataformat'] = 'mp3'; break; } if (isset($FirstFrameThisfileInfo) && isset($FirstFrameThisfileInfo['mpeg']['audio']['bitrate_mode']) && ($FirstFrameThisfileInfo['mpeg']['audio']['bitrate_mode'] == 'vbr')) { if (!(abs($info['audio']['bitrate'] - $FirstFrameThisfileInfo['audio']['bitrate']) <= 1)) { // If there is garbage data between a valid VBR header frame and a sequence // of valid MPEG-audio frames the VBR data is no longer discarded. $info = $FirstFrameThisfileInfo; $info['avdataoffset'] = $FirstFrameAVDataOffset; $info['fileformat'] = 'mp3'; $info['audio']['dataformat'] = 'mp3'; $dummy = $info; unset($dummy['mpeg']['audio']); $GarbageOffsetStart = $FirstFrameAVDataOffset + $FirstFrameThisfileInfo['mpeg']['audio']['framelength']; $GarbageOffsetEnd = $avdataoffset + $SynchSeekOffset; if ($this->decodeMPEGaudioHeader($GarbageOffsetEnd, $dummy, true, true)) { $info = $dummy; $info['avdataoffset'] = $GarbageOffsetEnd; $this->warning('apparently-valid VBR header not used because could not find '.$this->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); } else { $this->warning('using data from VBR header even though could not find '.$this->mp3_valid_check_frames.' consecutive MPEG-audio frames immediately after VBR header (garbage data for '.($GarbageOffsetEnd - $GarbageOffsetStart).' bytes between '.$GarbageOffsetStart.' and '.$GarbageOffsetEnd.')'); } } } if (isset($info['mpeg']['audio']['bitrate_mode']) && ($info['mpeg']['audio']['bitrate_mode'] == 'vbr') && !isset($info['mpeg']['audio']['VBR_method'])) { // VBR file with no VBR header $BitrateHistogram = true; }
// Definitively set VBR vs CBR, even if the Xing/LAME/VBRI header says differently $distinct_bitrates = 0; foreach ($info['mpeg']['audio']['bitrate_distribution'] as $bitrate_value => $bitrate_count) { if ($bitrate_count > 0) { $distinct_bitrates++; } } if ($distinct_bitrates > 1) { $info['mpeg']['audio']['bitrate_mode'] = 'vbr'; } else { $info['mpeg']['audio']['bitrate_mode'] = 'cbr'; } $info['audio']['bitrate_mode'] = $info['mpeg']['audio']['bitrate_mode'];
}
break; // exit while() } }
$SynchSeekOffset++; if (($avdataoffset + $SynchSeekOffset) >= $info['avdataend']) { // end of file/data
if (empty($info['mpeg']['audio'])) {
$this->error('could not find valid MPEG synch before end of file'); if (isset($info['audio']['bitrate'])) { unset($info['audio']['bitrate']); } if (isset($info['mpeg']['audio'])) { unset($info['mpeg']['audio']); } if (isset($info['mpeg']) && (!is_array($info['mpeg']) || empty($info['mpeg']))) { unset($info['mpeg']); } return false;
if (isset($MPEGaudioVersionLookup[$rawarray['version']])) { $decodedVersion = $MPEGaudioVersionLookup[$rawarray['version']]; } else { echo ($echoerrors ? "\n".'invalid Version ('.$rawarray['version'].')' : ''); return false; } if (isset($MPEGaudioLayerLookup[$rawarray['layer']])) { $decodedLayer = $MPEGaudioLayerLookup[$rawarray['layer']]; } else { echo ($echoerrors ? "\n".'invalid Layer ('.$rawarray['layer'].')' : ''); return false; } if (!isset($MPEGaudioBitrateLookup[$decodedVersion][$decodedLayer][$rawarray['bitrate']])) { echo ($echoerrors ? "\n".'invalid Bitrate ('.$rawarray['bitrate'].')' : ''); if ($rawarray['bitrate'] == 15) { // known issue in LAME 3.90 - 3.93.1 where free-format has bitrate ID of 15 instead of 0 // let it go through here otherwise file will not be identified if (!$allowBitrate15) { return false; } } else { return false; } } if (!isset($MPEGaudioFrequencyLookup[$decodedVersion][$rawarray['sample_rate']])) { echo ($echoerrors ? "\n".'invalid Frequency ('.$rawarray['sample_rate'].')' : ''); return false; } if (!isset($MPEGaudioChannelModeLookup[$rawarray['channelmode']])) { echo ($echoerrors ? "\n".'invalid ChannelMode ('.$rawarray['channelmode'].')' : ''); return false; } if (!isset($MPEGaudioModeExtensionLookup[$decodedLayer][$rawarray['modeextension']])) { echo ($echoerrors ? "\n".'invalid Mode Extension ('.$rawarray['modeextension'].')' : ''); return false; } if (!isset($MPEGaudioEmphasisLookup[$rawarray['emphasis']])) { echo ($echoerrors ? "\n".'invalid Emphasis ('.$rawarray['emphasis'].')' : ''); return false; } // These are just either set or not set, you can't mess that up :) // $rawarray['protection']; // $rawarray['padding']; // $rawarray['private']; // $rawarray['copyright']; // $rawarray['original'];
return true; }
/** * @param string $Header4Bytes * * @return array|false */ public static function MPEGaudioHeaderDecode($Header4Bytes) { // AAAA AAAA AAAB BCCD EEEE FFGH IIJJ KLMM // A - Frame sync (all bits set) // B - MPEG Audio version ID // C - Layer description // D - Protection bit // E - Bitrate index // F - Sampling rate frequency index // G - Padding bit // H - Private bit // I - Channel Mode // J - Mode extension (Only if Joint stereo) // K - Copyright // L - Original // M - Emphasis
/** * @param array $LAMEtag * * @return string */ public static function LAMEpresetUsedLookup($LAMEtag) {
if ($LAMEtag['preset_used_id'] == 0) { // no preset used (LAME >=3.93) // no preset recorded (LAME <3.93) return ''; } $LAMEpresetUsedLookup = array();
///// THIS PART CANNOT BE STATIC . for ($i = 8; $i <= 320; $i++) { switch ($LAMEtag['vbr_method']) { case 'cbr': $LAMEpresetUsedLookup[$i] = '--alt-preset '.$LAMEtag['vbr_method'].' '.$i; break; case 'abr': default: // other VBR modes shouldn't be here(?) $LAMEpresetUsedLookup[$i] = '--alt-preset '.$i; break; } }
// named old-style presets (studio, phone, voice, etc) are handled in GuessEncoderOptions()
// named alt-presets $LAMEpresetUsedLookup[1000] = '--r3mix'; $LAMEpresetUsedLookup[1001] = '--alt-preset standard'; $LAMEpresetUsedLookup[1002] = '--alt-preset extreme'; $LAMEpresetUsedLookup[1003] = '--alt-preset insane'; $LAMEpresetUsedLookup[1004] = '--alt-preset fast standard'; $LAMEpresetUsedLookup[1005] = '--alt-preset fast extreme'; $LAMEpresetUsedLookup[1006] = '--alt-preset medium'; $LAMEpresetUsedLookup[1007] = '--alt-preset fast medium';