File manager - Edit - /home/thefreecuj/www/ID3.tar
Back
module.audio-video.asf.php 0000644 00000411220 15054343026 0011520 0 ustar 00 <?php ///////////////////////////////////////////////////////////////// /// 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-video.asf.php // // module for analyzing ASF, WMA and WMV files // // dependencies: module.audio-video.riff.php // // /// ///////////////////////////////////////////////////////////////// if (!defined('GETID3_INCLUDEPATH')) { // prevent path-exposing attacks that access modules directly on public webservers exit; } getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.audio-video.riff.php', __FILE__, true); class getid3_asf extends getid3_handler { protected static $ASFIndexParametersObjectIndexSpecifiersIndexTypes = array( 1 => 'Nearest Past Data Packet', 2 => 'Nearest Past Media Object', 3 => 'Nearest Past Cleanpoint' ); protected static $ASFMediaObjectIndexParametersObjectIndexSpecifiersIndexTypes = array( 1 => 'Nearest Past Data Packet', 2 => 'Nearest Past Media Object', 3 => 'Nearest Past Cleanpoint', 0xFF => 'Frame Number Offset' ); protected static $ASFTimecodeIndexParametersObjectIndexSpecifiersIndexTypes = array( 2 => 'Nearest Past Media Object', 3 => 'Nearest Past Cleanpoint' ); /** * @param getID3 $getid3 */ public function __construct(getID3 $getid3) { parent::__construct($getid3); // extends getid3_handler::__construct() // initialize all GUID constants $GUIDarray = $this->KnownGUIDs(); foreach ($GUIDarray as $GUIDname => $hexstringvalue) { if (!defined($GUIDname)) { define($GUIDname, $this->GUIDtoBytestring($hexstringvalue)); } } } /** * @return bool */ public function Analyze() { $info = &$this->getid3->info; // Shortcuts $thisfile_audio = &$info['audio']; $thisfile_video = &$info['video']; $info['asf'] = array(); $thisfile_asf = &$info['asf']; $thisfile_asf['comments'] = array(); $thisfile_asf_comments = &$thisfile_asf['comments']; $thisfile_asf['header_object'] = array(); $thisfile_asf_headerobject = &$thisfile_asf['header_object']; // ASF structure: // * Header Object [required] // * File Properties Object [required] (global file attributes) // * Stream Properties Object [required] (defines media stream & characteristics) // * Header Extension Object [required] (additional functionality) // * Content Description Object (bibliographic information) // * Script Command Object (commands for during playback) // * Marker Object (named jumped points within the file) // * Data Object [required] // * Data Packets // * Index Object // Header Object: (mandatory, one only) // Field Name Field Type Size (bits) // Object ID GUID 128 // GUID for header object - GETID3_ASF_Header_Object // Object Size QWORD 64 // size of header object, including 30 bytes of Header Object header // Number of Header Objects DWORD 32 // number of objects in header object // Reserved1 BYTE 8 // hardcoded: 0x01 // Reserved2 BYTE 8 // hardcoded: 0x02 $info['fileformat'] = 'asf'; $this->fseek($info['avdataoffset']); $HeaderObjectData = $this->fread(30); $thisfile_asf_headerobject['objectid'] = substr($HeaderObjectData, 0, 16); $thisfile_asf_headerobject['objectid_guid'] = $this->BytestringToGUID($thisfile_asf_headerobject['objectid']); if ($thisfile_asf_headerobject['objectid'] != GETID3_ASF_Header_Object) { unset($info['fileformat'], $info['asf']); return $this->error('ASF header GUID {'.$this->BytestringToGUID($thisfile_asf_headerobject['objectid']).'} does not match expected "GETID3_ASF_Header_Object" GUID {'.$this->BytestringToGUID(GETID3_ASF_Header_Object).'}'); } $thisfile_asf_headerobject['objectsize'] = getid3_lib::LittleEndian2Int(substr($HeaderObjectData, 16, 8)); $thisfile_asf_headerobject['headerobjects'] = getid3_lib::LittleEndian2Int(substr($HeaderObjectData, 24, 4)); $thisfile_asf_headerobject['reserved1'] = getid3_lib::LittleEndian2Int(substr($HeaderObjectData, 28, 1)); $thisfile_asf_headerobject['reserved2'] = getid3_lib::LittleEndian2Int(substr($HeaderObjectData, 29, 1)); $NextObjectOffset = $this->ftell(); $ASFHeaderData = $this->fread($thisfile_asf_headerobject['objectsize'] - 30); $offset = 0; $thisfile_asf_streambitratepropertiesobject = array(); $thisfile_asf_codeclistobject = array(); $StreamPropertiesObjectData = array(); for ($HeaderObjectsCounter = 0; $HeaderObjectsCounter < $thisfile_asf_headerobject['headerobjects']; $HeaderObjectsCounter++) { $NextObjectGUID = substr($ASFHeaderData, $offset, 16); $offset += 16; $NextObjectGUIDtext = $this->BytestringToGUID($NextObjectGUID); $NextObjectSize = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 8)); $offset += 8; switch ($NextObjectGUID) { case GETID3_ASF_File_Properties_Object: // File Properties Object: (mandatory, one only) // Field Name Field Type Size (bits) // Object ID GUID 128 // GUID for file properties object - GETID3_ASF_File_Properties_Object // Object Size QWORD 64 // size of file properties object, including 104 bytes of File Properties Object header // File ID GUID 128 // unique ID - identical to File ID in Data Object // File Size QWORD 64 // entire file in bytes. Invalid if Broadcast Flag == 1 // Creation Date QWORD 64 // date & time of file creation. Maybe invalid if Broadcast Flag == 1 // Data Packets Count QWORD 64 // number of data packets in Data Object. Invalid if Broadcast Flag == 1 // Play Duration QWORD 64 // playtime, in 100-nanosecond units. Invalid if Broadcast Flag == 1 // Send Duration QWORD 64 // time needed to send file, in 100-nanosecond units. Players can ignore this value. Invalid if Broadcast Flag == 1 // Preroll QWORD 64 // time to buffer data before starting to play file, in 1-millisecond units. If <> 0, PlayDuration and PresentationTime have been offset by this amount // Flags DWORD 32 // // * Broadcast Flag bits 1 (0x01) // file is currently being written, some header values are invalid // * Seekable Flag bits 1 (0x02) // is file seekable // * Reserved bits 30 (0xFFFFFFFC) // reserved - set to zero // Minimum Data Packet Size DWORD 32 // in bytes. should be same as Maximum Data Packet Size. Invalid if Broadcast Flag == 1 // Maximum Data Packet Size DWORD 32 // in bytes. should be same as Minimum Data Packet Size. Invalid if Broadcast Flag == 1 // Maximum Bitrate DWORD 32 // maximum instantaneous bitrate in bits per second for entire file, including all data streams and ASF overhead // shortcut $thisfile_asf['file_properties_object'] = array(); $thisfile_asf_filepropertiesobject = &$thisfile_asf['file_properties_object']; $thisfile_asf_filepropertiesobject['offset'] = $NextObjectOffset + $offset; $thisfile_asf_filepropertiesobject['objectid'] = $NextObjectGUID; $thisfile_asf_filepropertiesobject['objectid_guid'] = $NextObjectGUIDtext; $thisfile_asf_filepropertiesobject['objectsize'] = $NextObjectSize; $thisfile_asf_filepropertiesobject['fileid'] = substr($ASFHeaderData, $offset, 16); $offset += 16; $thisfile_asf_filepropertiesobject['fileid_guid'] = $this->BytestringToGUID($thisfile_asf_filepropertiesobject['fileid']); $thisfile_asf_filepropertiesobject['filesize'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 8)); $offset += 8; $thisfile_asf_filepropertiesobject['creation_date'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 8)); $thisfile_asf_filepropertiesobject['creation_date_unix'] = $this->FILETIMEtoUNIXtime($thisfile_asf_filepropertiesobject['creation_date']); $offset += 8; $thisfile_asf_filepropertiesobject['data_packets'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 8)); $offset += 8; $thisfile_asf_filepropertiesobject['play_duration'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 8)); $offset += 8; $thisfile_asf_filepropertiesobject['send_duration'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 8)); $offset += 8; $thisfile_asf_filepropertiesobject['preroll'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 8)); $offset += 8; $thisfile_asf_filepropertiesobject['flags_raw'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 4)); $offset += 4; $thisfile_asf_filepropertiesobject['flags']['broadcast'] = (bool) ($thisfile_asf_filepropertiesobject['flags_raw'] & 0x0001); $thisfile_asf_filepropertiesobject['flags']['seekable'] = (bool) ($thisfile_asf_filepropertiesobject['flags_raw'] & 0x0002); $thisfile_asf_filepropertiesobject['min_packet_size'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 4)); $offset += 4; $thisfile_asf_filepropertiesobject['max_packet_size'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 4)); $offset += 4; $thisfile_asf_filepropertiesobject['max_bitrate'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 4)); $offset += 4; if ($thisfile_asf_filepropertiesobject['flags']['broadcast']) { // broadcast flag is set, some values invalid unset($thisfile_asf_filepropertiesobject['filesize']); unset($thisfile_asf_filepropertiesobject['data_packets']); unset($thisfile_asf_filepropertiesobject['play_duration']); unset($thisfile_asf_filepropertiesobject['send_duration']); unset($thisfile_asf_filepropertiesobject['min_packet_size']); unset($thisfile_asf_filepropertiesobject['max_packet_size']); } else { // broadcast flag NOT set, perform calculations $info['playtime_seconds'] = ($thisfile_asf_filepropertiesobject['play_duration'] / 10000000) - ($thisfile_asf_filepropertiesobject['preroll'] / 1000); //$info['bitrate'] = $thisfile_asf_filepropertiesobject['max_bitrate']; $info['bitrate'] = getid3_lib::SafeDiv($thisfile_asf_filepropertiesobject['filesize'] * 8, $info['playtime_seconds']); } break; case GETID3_ASF_Stream_Properties_Object: // Stream Properties Object: (mandatory, one per media stream) // Field Name Field Type Size (bits) // Object ID GUID 128 // GUID for stream properties object - GETID3_ASF_Stream_Properties_Object // Object Size QWORD 64 // size of stream properties object, including 78 bytes of Stream Properties Object header // Stream Type GUID 128 // GETID3_ASF_Audio_Media, GETID3_ASF_Video_Media or GETID3_ASF_Command_Media // Error Correction Type GUID 128 // GETID3_ASF_Audio_Spread for audio-only streams, GETID3_ASF_No_Error_Correction for other stream types // Time Offset QWORD 64 // 100-nanosecond units. typically zero. added to all timestamps of samples in the stream // Type-Specific Data Length DWORD 32 // number of bytes for Type-Specific Data field // Error Correction Data Length DWORD 32 // number of bytes for Error Correction Data field // Flags WORD 16 // // * Stream Number bits 7 (0x007F) // number of this stream. 1 <= valid <= 127 // * Reserved bits 8 (0x7F80) // reserved - set to zero // * Encrypted Content Flag bits 1 (0x8000) // stream contents encrypted if set // Reserved DWORD 32 // reserved - set to zero // Type-Specific Data BYTESTREAM variable // type-specific format data, depending on value of Stream Type // Error Correction Data BYTESTREAM variable // error-correction-specific format data, depending on value of Error Correct Type // There is one GETID3_ASF_Stream_Properties_Object for each stream (audio, video) but the // stream number isn't known until halfway through decoding the structure, hence it // it is decoded to a temporary variable and then stuck in the appropriate index later $StreamPropertiesObjectData['offset'] = $NextObjectOffset + $offset; $StreamPropertiesObjectData['objectid'] = $NextObjectGUID; $StreamPropertiesObjectData['objectid_guid'] = $NextObjectGUIDtext; $StreamPropertiesObjectData['objectsize'] = $NextObjectSize; $StreamPropertiesObjectData['stream_type'] = substr($ASFHeaderData, $offset, 16); $offset += 16; $StreamPropertiesObjectData['stream_type_guid'] = $this->BytestringToGUID($StreamPropertiesObjectData['stream_type']); $StreamPropertiesObjectData['error_correct_type'] = substr($ASFHeaderData, $offset, 16); $offset += 16; $StreamPropertiesObjectData['error_correct_guid'] = $this->BytestringToGUID($StreamPropertiesObjectData['error_correct_type']); $StreamPropertiesObjectData['time_offset'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 8)); $offset += 8; $StreamPropertiesObjectData['type_data_length'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 4)); $offset += 4; $StreamPropertiesObjectData['error_data_length'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 4)); $offset += 4; $StreamPropertiesObjectData['flags_raw'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2)); $offset += 2; $StreamPropertiesObjectStreamNumber = $StreamPropertiesObjectData['flags_raw'] & 0x007F; $StreamPropertiesObjectData['flags']['encrypted'] = (bool) ($StreamPropertiesObjectData['flags_raw'] & 0x8000); $offset += 4; // reserved - DWORD $StreamPropertiesObjectData['type_specific_data'] = substr($ASFHeaderData, $offset, $StreamPropertiesObjectData['type_data_length']); $offset += $StreamPropertiesObjectData['type_data_length']; $StreamPropertiesObjectData['error_correct_data'] = substr($ASFHeaderData, $offset, $StreamPropertiesObjectData['error_data_length']); $offset += $StreamPropertiesObjectData['error_data_length']; switch ($StreamPropertiesObjectData['stream_type']) { case GETID3_ASF_Audio_Media: $thisfile_audio['dataformat'] = (!empty($thisfile_audio['dataformat']) ? $thisfile_audio['dataformat'] : 'asf'); $thisfile_audio['bitrate_mode'] = (!empty($thisfile_audio['bitrate_mode']) ? $thisfile_audio['bitrate_mode'] : 'cbr'); $audiodata = getid3_riff::parseWAVEFORMATex(substr($StreamPropertiesObjectData['type_specific_data'], 0, 16)); unset($audiodata['raw']); $thisfile_audio = getid3_lib::array_merge_noclobber($audiodata, $thisfile_audio); break; case GETID3_ASF_Video_Media: $thisfile_video['dataformat'] = (!empty($thisfile_video['dataformat']) ? $thisfile_video['dataformat'] : 'asf'); $thisfile_video['bitrate_mode'] = (!empty($thisfile_video['bitrate_mode']) ? $thisfile_video['bitrate_mode'] : 'cbr'); break; case GETID3_ASF_Command_Media: default: // do nothing break; } $thisfile_asf['stream_properties_object'][$StreamPropertiesObjectStreamNumber] = $StreamPropertiesObjectData; unset($StreamPropertiesObjectData); // clear for next stream, if any break; case GETID3_ASF_Header_Extension_Object: // Header Extension Object: (mandatory, one only) // Field Name Field Type Size (bits) // Object ID GUID 128 // GUID for Header Extension object - GETID3_ASF_Header_Extension_Object // Object Size QWORD 64 // size of Header Extension object, including 46 bytes of Header Extension Object header // Reserved Field 1 GUID 128 // hardcoded: GETID3_ASF_Reserved_1 // Reserved Field 2 WORD 16 // hardcoded: 0x00000006 // Header Extension Data Size DWORD 32 // in bytes. valid: 0, or > 24. equals object size minus 46 // Header Extension Data BYTESTREAM variable // array of zero or more extended header objects // shortcut $thisfile_asf['header_extension_object'] = array(); $thisfile_asf_headerextensionobject = &$thisfile_asf['header_extension_object']; $thisfile_asf_headerextensionobject['offset'] = $NextObjectOffset + $offset; $thisfile_asf_headerextensionobject['objectid'] = $NextObjectGUID; $thisfile_asf_headerextensionobject['objectid_guid'] = $NextObjectGUIDtext; $thisfile_asf_headerextensionobject['objectsize'] = $NextObjectSize; $thisfile_asf_headerextensionobject['reserved_1'] = substr($ASFHeaderData, $offset, 16); $offset += 16; $thisfile_asf_headerextensionobject['reserved_1_guid'] = $this->BytestringToGUID($thisfile_asf_headerextensionobject['reserved_1']); if ($thisfile_asf_headerextensionobject['reserved_1'] != GETID3_ASF_Reserved_1) { $this->warning('header_extension_object.reserved_1 GUID ('.$this->BytestringToGUID($thisfile_asf_headerextensionobject['reserved_1']).') does not match expected "GETID3_ASF_Reserved_1" GUID ('.$this->BytestringToGUID(GETID3_ASF_Reserved_1).')'); //return false; break; } $thisfile_asf_headerextensionobject['reserved_2'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2)); $offset += 2; if ($thisfile_asf_headerextensionobject['reserved_2'] != 6) { $this->warning('header_extension_object.reserved_2 ('.$thisfile_asf_headerextensionobject['reserved_2'].') does not match expected value of "6"'); //return false; break; } $thisfile_asf_headerextensionobject['extension_data_size'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 4)); $offset += 4; $thisfile_asf_headerextensionobject['extension_data'] = substr($ASFHeaderData, $offset, $thisfile_asf_headerextensionobject['extension_data_size']); $unhandled_sections = 0; $thisfile_asf_headerextensionobject['extension_data_parsed'] = $this->HeaderExtensionObjectDataParse($thisfile_asf_headerextensionobject['extension_data'], $unhandled_sections); if ($unhandled_sections === 0) { unset($thisfile_asf_headerextensionobject['extension_data']); } $offset += $thisfile_asf_headerextensionobject['extension_data_size']; break; case GETID3_ASF_Codec_List_Object: // Codec List Object: (optional, one only) // Field Name Field Type Size (bits) // Object ID GUID 128 // GUID for Codec List object - GETID3_ASF_Codec_List_Object // Object Size QWORD 64 // size of Codec List object, including 44 bytes of Codec List Object header // Reserved GUID 128 // hardcoded: 86D15241-311D-11D0-A3A4-00A0C90348F6 // Codec Entries Count DWORD 32 // number of entries in Codec Entries array // Codec Entries array of: variable // // * Type WORD 16 // 0x0001 = Video Codec, 0x0002 = Audio Codec, 0xFFFF = Unknown Codec // * Codec Name Length WORD 16 // number of Unicode characters stored in the Codec Name field // * Codec Name WCHAR variable // array of Unicode characters - name of codec used to create the content // * Codec Description Length WORD 16 // number of Unicode characters stored in the Codec Description field // * Codec Description WCHAR variable // array of Unicode characters - description of format used to create the content // * Codec Information Length WORD 16 // number of Unicode characters stored in the Codec Information field // * Codec Information BYTESTREAM variable // opaque array of information bytes about the codec used to create the content // shortcut $thisfile_asf['codec_list_object'] = array(); /** @var mixed[] $thisfile_asf_codeclistobject */ $thisfile_asf_codeclistobject = &$thisfile_asf['codec_list_object']; $thisfile_asf_codeclistobject['offset'] = $NextObjectOffset + $offset; $thisfile_asf_codeclistobject['objectid'] = $NextObjectGUID; $thisfile_asf_codeclistobject['objectid_guid'] = $NextObjectGUIDtext; $thisfile_asf_codeclistobject['objectsize'] = $NextObjectSize; $thisfile_asf_codeclistobject['reserved'] = substr($ASFHeaderData, $offset, 16); $offset += 16; $thisfile_asf_codeclistobject['reserved_guid'] = $this->BytestringToGUID($thisfile_asf_codeclistobject['reserved']); if ($thisfile_asf_codeclistobject['reserved'] != $this->GUIDtoBytestring('86D15241-311D-11D0-A3A4-00A0C90348F6')) { $this->warning('codec_list_object.reserved GUID {'.$this->BytestringToGUID($thisfile_asf_codeclistobject['reserved']).'} does not match expected "GETID3_ASF_Reserved_1" GUID {86D15241-311D-11D0-A3A4-00A0C90348F6}'); //return false; break; } $thisfile_asf_codeclistobject['codec_entries_count'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 4)); if ($thisfile_asf_codeclistobject['codec_entries_count'] > 0) { $thisfile_asf_codeclistobject['codec_entries'] = array(); } $offset += 4; for ($CodecEntryCounter = 0; $CodecEntryCounter < $thisfile_asf_codeclistobject['codec_entries_count']; $CodecEntryCounter++) { // shortcut $thisfile_asf_codeclistobject['codec_entries'][$CodecEntryCounter] = array(); $thisfile_asf_codeclistobject_codecentries_current = &$thisfile_asf_codeclistobject['codec_entries'][$CodecEntryCounter]; $thisfile_asf_codeclistobject_codecentries_current['type_raw'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2)); $offset += 2; $thisfile_asf_codeclistobject_codecentries_current['type'] = self::codecListObjectTypeLookup($thisfile_asf_codeclistobject_codecentries_current['type_raw']); $CodecNameLength = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2)) * 2; // 2 bytes per character $offset += 2; $thisfile_asf_codeclistobject_codecentries_current['name'] = substr($ASFHeaderData, $offset, $CodecNameLength); $offset += $CodecNameLength; $CodecDescriptionLength = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2)) * 2; // 2 bytes per character $offset += 2; $thisfile_asf_codeclistobject_codecentries_current['description'] = substr($ASFHeaderData, $offset, $CodecDescriptionLength); $offset += $CodecDescriptionLength; $CodecInformationLength = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2)); $offset += 2; $thisfile_asf_codeclistobject_codecentries_current['information'] = substr($ASFHeaderData, $offset, $CodecInformationLength); $offset += $CodecInformationLength; if ($thisfile_asf_codeclistobject_codecentries_current['type_raw'] == 2) { // audio codec if (strpos($thisfile_asf_codeclistobject_codecentries_current['description'], ',') === false) { $this->warning('[asf][codec_list_object][codec_entries]['.$CodecEntryCounter.'][description] expected to contain comma-separated list of parameters: "'.$thisfile_asf_codeclistobject_codecentries_current['description'].'"'); } else { list($AudioCodecBitrate, $AudioCodecFrequency, $AudioCodecChannels) = explode(',', $this->TrimConvert($thisfile_asf_codeclistobject_codecentries_current['description'])); $thisfile_audio['codec'] = $this->TrimConvert($thisfile_asf_codeclistobject_codecentries_current['name']); if (!isset($thisfile_audio['bitrate']) && strstr($AudioCodecBitrate, 'kbps')) { $thisfile_audio['bitrate'] = (int) trim(str_replace('kbps', '', $AudioCodecBitrate)) * 1000; } //if (!isset($thisfile_video['bitrate']) && isset($thisfile_audio['bitrate']) && isset($thisfile_asf['file_properties_object']['max_bitrate']) && ($thisfile_asf_codeclistobject['codec_entries_count'] > 1)) { if (empty($thisfile_video['bitrate']) && !empty($thisfile_audio['bitrate']) && !empty($info['bitrate'])) { //$thisfile_video['bitrate'] = $thisfile_asf['file_properties_object']['max_bitrate'] - $thisfile_audio['bitrate']; $thisfile_video['bitrate'] = $info['bitrate'] - $thisfile_audio['bitrate']; } $AudioCodecFrequency = (int) trim(str_replace('kHz', '', $AudioCodecFrequency)); switch ($AudioCodecFrequency) { case 8: case 8000: $thisfile_audio['sample_rate'] = 8000; break; case 11: case 11025: $thisfile_audio['sample_rate'] = 11025; break; case 12: case 12000: $thisfile_audio['sample_rate'] = 12000; break; case 16: case 16000: $thisfile_audio['sample_rate'] = 16000; break; case 22: case 22050: $thisfile_audio['sample_rate'] = 22050; break; case 24: case 24000: $thisfile_audio['sample_rate'] = 24000; break; case 32: case 32000: $thisfile_audio['sample_rate'] = 32000; break; case 44: case 441000: $thisfile_audio['sample_rate'] = 44100; break; case 48: case 48000: $thisfile_audio['sample_rate'] = 48000; break; default: $this->warning('unknown frequency: "'.$AudioCodecFrequency.'" ('.$this->TrimConvert($thisfile_asf_codeclistobject_codecentries_current['description']).')'); break; } if (!isset($thisfile_audio['channels'])) { if (strstr($AudioCodecChannels, 'stereo')) { $thisfile_audio['channels'] = 2; } elseif (strstr($AudioCodecChannels, 'mono')) { $thisfile_audio['channels'] = 1; } } } } } break; case GETID3_ASF_Script_Command_Object: // Script Command Object: (optional, one only) // Field Name Field Type Size (bits) // Object ID GUID 128 // GUID for Script Command object - GETID3_ASF_Script_Command_Object // Object Size QWORD 64 // size of Script Command object, including 44 bytes of Script Command Object header // Reserved GUID 128 // hardcoded: 4B1ACBE3-100B-11D0-A39B-00A0C90348F6 // Commands Count WORD 16 // number of Commands structures in the Script Commands Objects // Command Types Count WORD 16 // number of Command Types structures in the Script Commands Objects // Command Types array of: variable // // * Command Type Name Length WORD 16 // number of Unicode characters for Command Type Name // * Command Type Name WCHAR variable // array of Unicode characters - name of a type of command // Commands array of: variable // // * Presentation Time DWORD 32 // presentation time of that command, in milliseconds // * Type Index WORD 16 // type of this command, as a zero-based index into the array of Command Types of this object // * Command Name Length WORD 16 // number of Unicode characters for Command Name // * Command Name WCHAR variable // array of Unicode characters - name of this command // shortcut $thisfile_asf['script_command_object'] = array(); $thisfile_asf_scriptcommandobject = &$thisfile_asf['script_command_object']; $thisfile_asf_scriptcommandobject['offset'] = $NextObjectOffset + $offset; $thisfile_asf_scriptcommandobject['objectid'] = $NextObjectGUID; $thisfile_asf_scriptcommandobject['objectid_guid'] = $NextObjectGUIDtext; $thisfile_asf_scriptcommandobject['objectsize'] = $NextObjectSize; $thisfile_asf_scriptcommandobject['reserved'] = substr($ASFHeaderData, $offset, 16); $offset += 16; $thisfile_asf_scriptcommandobject['reserved_guid'] = $this->BytestringToGUID($thisfile_asf_scriptcommandobject['reserved']); if ($thisfile_asf_scriptcommandobject['reserved'] != $this->GUIDtoBytestring('4B1ACBE3-100B-11D0-A39B-00A0C90348F6')) { $this->warning('script_command_object.reserved GUID {'.$this->BytestringToGUID($thisfile_asf_scriptcommandobject['reserved']).'} does not match expected "GETID3_ASF_Reserved_1" GUID {4B1ACBE3-100B-11D0-A39B-00A0C90348F6}'); //return false; break; } $thisfile_asf_scriptcommandobject['commands_count'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2)); $offset += 2; $thisfile_asf_scriptcommandobject['command_types_count'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2)); $offset += 2; for ($CommandTypesCounter = 0; $CommandTypesCounter < $thisfile_asf_scriptcommandobject['command_types_count']; $CommandTypesCounter++) { $CommandTypeNameLength = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2)) * 2; // 2 bytes per character $offset += 2; $thisfile_asf_scriptcommandobject['command_types'][$CommandTypesCounter]['name'] = substr($ASFHeaderData, $offset, $CommandTypeNameLength); $offset += $CommandTypeNameLength; } for ($CommandsCounter = 0; $CommandsCounter < $thisfile_asf_scriptcommandobject['commands_count']; $CommandsCounter++) { $thisfile_asf_scriptcommandobject['commands'][$CommandsCounter]['presentation_time'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 4)); $offset += 4; $thisfile_asf_scriptcommandobject['commands'][$CommandsCounter]['type_index'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2)); $offset += 2; $CommandTypeNameLength = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2)) * 2; // 2 bytes per character $offset += 2; $thisfile_asf_scriptcommandobject['commands'][$CommandsCounter]['name'] = substr($ASFHeaderData, $offset, $CommandTypeNameLength); $offset += $CommandTypeNameLength; } break; case GETID3_ASF_Marker_Object: // Marker Object: (optional, one only) // Field Name Field Type Size (bits) // Object ID GUID 128 // GUID for Marker object - GETID3_ASF_Marker_Object // Object Size QWORD 64 // size of Marker object, including 48 bytes of Marker Object header // Reserved GUID 128 // hardcoded: 4CFEDB20-75F6-11CF-9C0F-00A0C90349CB // Markers Count DWORD 32 // number of Marker structures in Marker Object // Reserved WORD 16 // hardcoded: 0x0000 // Name Length WORD 16 // number of bytes in the Name field // Name WCHAR variable // name of the Marker Object // Markers array of: variable // // * Offset QWORD 64 // byte offset into Data Object // * Presentation Time QWORD 64 // in 100-nanosecond units // * Entry Length WORD 16 // length in bytes of (Send Time + Flags + Marker Description Length + Marker Description + Padding) // * Send Time DWORD 32 // in milliseconds // * Flags DWORD 32 // hardcoded: 0x00000000 // * Marker Description Length DWORD 32 // number of bytes in Marker Description field // * Marker Description WCHAR variable // array of Unicode characters - description of marker entry // * Padding BYTESTREAM variable // optional padding bytes // shortcut $thisfile_asf['marker_object'] = array(); $thisfile_asf_markerobject = &$thisfile_asf['marker_object']; $thisfile_asf_markerobject['offset'] = $NextObjectOffset + $offset; $thisfile_asf_markerobject['objectid'] = $NextObjectGUID; $thisfile_asf_markerobject['objectid_guid'] = $NextObjectGUIDtext; $thisfile_asf_markerobject['objectsize'] = $NextObjectSize; $thisfile_asf_markerobject['reserved'] = substr($ASFHeaderData, $offset, 16); $offset += 16; $thisfile_asf_markerobject['reserved_guid'] = $this->BytestringToGUID($thisfile_asf_markerobject['reserved']); if ($thisfile_asf_markerobject['reserved'] != $this->GUIDtoBytestring('4CFEDB20-75F6-11CF-9C0F-00A0C90349CB')) { $this->warning('marker_object.reserved GUID {'.$this->BytestringToGUID($thisfile_asf_markerobject['reserved']).'} does not match expected "GETID3_ASF_Reserved_1" GUID {4CFEDB20-75F6-11CF-9C0F-00A0C90349CB}'); break; } $thisfile_asf_markerobject['markers_count'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 4)); $offset += 4; $thisfile_asf_markerobject['reserved_2'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2)); $offset += 2; if ($thisfile_asf_markerobject['reserved_2'] != 0) { $this->warning('marker_object.reserved_2 ('.$thisfile_asf_markerobject['reserved_2'].') does not match expected value of "0"'); break; } $thisfile_asf_markerobject['name_length'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2)); $offset += 2; $thisfile_asf_markerobject['name'] = substr($ASFHeaderData, $offset, $thisfile_asf_markerobject['name_length']); $offset += $thisfile_asf_markerobject['name_length']; for ($MarkersCounter = 0; $MarkersCounter < $thisfile_asf_markerobject['markers_count']; $MarkersCounter++) { $thisfile_asf_markerobject['markers'][$MarkersCounter]['offset'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 8)); $offset += 8; $thisfile_asf_markerobject['markers'][$MarkersCounter]['presentation_time'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 8)); $offset += 8; $thisfile_asf_markerobject['markers'][$MarkersCounter]['entry_length'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2)); $offset += 2; $thisfile_asf_markerobject['markers'][$MarkersCounter]['send_time'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 4)); $offset += 4; $thisfile_asf_markerobject['markers'][$MarkersCounter]['flags'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 4)); $offset += 4; $thisfile_asf_markerobject['markers'][$MarkersCounter]['marker_description_length'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 4)); $offset += 4; $thisfile_asf_markerobject['markers'][$MarkersCounter]['marker_description'] = substr($ASFHeaderData, $offset, $thisfile_asf_markerobject['markers'][$MarkersCounter]['marker_description_length']); $offset += $thisfile_asf_markerobject['markers'][$MarkersCounter]['marker_description_length']; $PaddingLength = $thisfile_asf_markerobject['markers'][$MarkersCounter]['entry_length'] - 4 - 4 - 4 - $thisfile_asf_markerobject['markers'][$MarkersCounter]['marker_description_length']; if ($PaddingLength > 0) { $thisfile_asf_markerobject['markers'][$MarkersCounter]['padding'] = substr($ASFHeaderData, $offset, $PaddingLength); $offset += $PaddingLength; } } break; case GETID3_ASF_Bitrate_Mutual_Exclusion_Object: // Bitrate Mutual Exclusion Object: (optional) // Field Name Field Type Size (bits) // Object ID GUID 128 // GUID for Bitrate Mutual Exclusion object - GETID3_ASF_Bitrate_Mutual_Exclusion_Object // Object Size QWORD 64 // size of Bitrate Mutual Exclusion object, including 42 bytes of Bitrate Mutual Exclusion Object header // Exlusion Type GUID 128 // nature of mutual exclusion relationship. one of: (GETID3_ASF_Mutex_Bitrate, GETID3_ASF_Mutex_Unknown) // Stream Numbers Count WORD 16 // number of video streams // Stream Numbers WORD variable // array of mutually exclusive video stream numbers. 1 <= valid <= 127 // shortcut $thisfile_asf['bitrate_mutual_exclusion_object'] = array(); $thisfile_asf_bitratemutualexclusionobject = &$thisfile_asf['bitrate_mutual_exclusion_object']; $thisfile_asf_bitratemutualexclusionobject['offset'] = $NextObjectOffset + $offset; $thisfile_asf_bitratemutualexclusionobject['objectid'] = $NextObjectGUID; $thisfile_asf_bitratemutualexclusionobject['objectid_guid'] = $NextObjectGUIDtext; $thisfile_asf_bitratemutualexclusionobject['objectsize'] = $NextObjectSize; $thisfile_asf_bitratemutualexclusionobject['reserved'] = substr($ASFHeaderData, $offset, 16); $thisfile_asf_bitratemutualexclusionobject['reserved_guid'] = $this->BytestringToGUID($thisfile_asf_bitratemutualexclusionobject['reserved']); $offset += 16; if (($thisfile_asf_bitratemutualexclusionobject['reserved'] != GETID3_ASF_Mutex_Bitrate) && ($thisfile_asf_bitratemutualexclusionobject['reserved'] != GETID3_ASF_Mutex_Unknown)) { $this->warning('bitrate_mutual_exclusion_object.reserved GUID {'.$this->BytestringToGUID($thisfile_asf_bitratemutualexclusionobject['reserved']).'} does not match expected "GETID3_ASF_Mutex_Bitrate" GUID {'.$this->BytestringToGUID(GETID3_ASF_Mutex_Bitrate).'} or "GETID3_ASF_Mutex_Unknown" GUID {'.$this->BytestringToGUID(GETID3_ASF_Mutex_Unknown).'}'); //return false; break; } $thisfile_asf_bitratemutualexclusionobject['stream_numbers_count'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2)); $offset += 2; for ($StreamNumberCounter = 0; $StreamNumberCounter < $thisfile_asf_bitratemutualexclusionobject['stream_numbers_count']; $StreamNumberCounter++) { $thisfile_asf_bitratemutualexclusionobject['stream_numbers'][$StreamNumberCounter] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2)); $offset += 2; } break; case GETID3_ASF_Error_Correction_Object: // Error Correction Object: (optional, one only) // Field Name Field Type Size (bits) // Object ID GUID 128 // GUID for Error Correction object - GETID3_ASF_Error_Correction_Object // Object Size QWORD 64 // size of Error Correction object, including 44 bytes of Error Correction Object header // Error Correction Type GUID 128 // type of error correction. one of: (GETID3_ASF_No_Error_Correction, GETID3_ASF_Audio_Spread) // Error Correction Data Length DWORD 32 // number of bytes in Error Correction Data field // Error Correction Data BYTESTREAM variable // structure depends on value of Error Correction Type field // shortcut $thisfile_asf['error_correction_object'] = array(); $thisfile_asf_errorcorrectionobject = &$thisfile_asf['error_correction_object']; $thisfile_asf_errorcorrectionobject['offset'] = $NextObjectOffset + $offset; $thisfile_asf_errorcorrectionobject['objectid'] = $NextObjectGUID; $thisfile_asf_errorcorrectionobject['objectid_guid'] = $NextObjectGUIDtext; $thisfile_asf_errorcorrectionobject['objectsize'] = $NextObjectSize; $thisfile_asf_errorcorrectionobject['error_correction_type'] = substr($ASFHeaderData, $offset, 16); $offset += 16; $thisfile_asf_errorcorrectionobject['error_correction_guid'] = $this->BytestringToGUID($thisfile_asf_errorcorrectionobject['error_correction_type']); $thisfile_asf_errorcorrectionobject['error_correction_data_length'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 4)); $offset += 4; switch ($thisfile_asf_errorcorrectionobject['error_correction_type']) { case GETID3_ASF_No_Error_Correction: // should be no data, but just in case there is, skip to the end of the field $offset += $thisfile_asf_errorcorrectionobject['error_correction_data_length']; break; case GETID3_ASF_Audio_Spread: // Field Name Field Type Size (bits) // Span BYTE 8 // number of packets over which audio will be spread. // Virtual Packet Length WORD 16 // size of largest audio payload found in audio stream // Virtual Chunk Length WORD 16 // size of largest audio payload found in audio stream // Silence Data Length WORD 16 // number of bytes in Silence Data field // Silence Data BYTESTREAM variable // hardcoded: 0x00 * (Silence Data Length) bytes $thisfile_asf_errorcorrectionobject['span'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 1)); $offset += 1; $thisfile_asf_errorcorrectionobject['virtual_packet_length'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2)); $offset += 2; $thisfile_asf_errorcorrectionobject['virtual_chunk_length'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2)); $offset += 2; $thisfile_asf_errorcorrectionobject['silence_data_length'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2)); $offset += 2; $thisfile_asf_errorcorrectionobject['silence_data'] = substr($ASFHeaderData, $offset, $thisfile_asf_errorcorrectionobject['silence_data_length']); $offset += $thisfile_asf_errorcorrectionobject['silence_data_length']; break; default: $this->warning('error_correction_object.error_correction_type GUID {'.$this->BytestringToGUID($thisfile_asf_errorcorrectionobject['error_correction_type']).'} does not match expected "GETID3_ASF_No_Error_Correction" GUID {'.$this->BytestringToGUID(GETID3_ASF_No_Error_Correction).'} or "GETID3_ASF_Audio_Spread" GUID {'.$this->BytestringToGUID(GETID3_ASF_Audio_Spread).'}'); //return false; break; } break; case GETID3_ASF_Content_Description_Object: // Content Description Object: (optional, one only) // Field Name Field Type Size (bits) // Object ID GUID 128 // GUID for Content Description object - GETID3_ASF_Content_Description_Object // Object Size QWORD 64 // size of Content Description object, including 34 bytes of Content Description Object header // Title Length WORD 16 // number of bytes in Title field // Author Length WORD 16 // number of bytes in Author field // Copyright Length WORD 16 // number of bytes in Copyright field // Description Length WORD 16 // number of bytes in Description field // Rating Length WORD 16 // number of bytes in Rating field // Title WCHAR 16 // array of Unicode characters - Title // Author WCHAR 16 // array of Unicode characters - Author // Copyright WCHAR 16 // array of Unicode characters - Copyright // Description WCHAR 16 // array of Unicode characters - Description // Rating WCHAR 16 // array of Unicode characters - Rating // shortcut $thisfile_asf['content_description_object'] = array(); $thisfile_asf_contentdescriptionobject = &$thisfile_asf['content_description_object']; $thisfile_asf_contentdescriptionobject['offset'] = $NextObjectOffset + $offset; $thisfile_asf_contentdescriptionobject['objectid'] = $NextObjectGUID; $thisfile_asf_contentdescriptionobject['objectid_guid'] = $NextObjectGUIDtext; $thisfile_asf_contentdescriptionobject['objectsize'] = $NextObjectSize; $thisfile_asf_contentdescriptionobject['title_length'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2)); $offset += 2; $thisfile_asf_contentdescriptionobject['author_length'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2)); $offset += 2; $thisfile_asf_contentdescriptionobject['copyright_length'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2)); $offset += 2; $thisfile_asf_contentdescriptionobject['description_length'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2)); $offset += 2; $thisfile_asf_contentdescriptionobject['rating_length'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2)); $offset += 2; $thisfile_asf_contentdescriptionobject['title'] = substr($ASFHeaderData, $offset, $thisfile_asf_contentdescriptionobject['title_length']); $offset += $thisfile_asf_contentdescriptionobject['title_length']; $thisfile_asf_contentdescriptionobject['author'] = substr($ASFHeaderData, $offset, $thisfile_asf_contentdescriptionobject['author_length']); $offset += $thisfile_asf_contentdescriptionobject['author_length']; $thisfile_asf_contentdescriptionobject['copyright'] = substr($ASFHeaderData, $offset, $thisfile_asf_contentdescriptionobject['copyright_length']); $offset += $thisfile_asf_contentdescriptionobject['copyright_length']; $thisfile_asf_contentdescriptionobject['description'] = substr($ASFHeaderData, $offset, $thisfile_asf_contentdescriptionobject['description_length']); $offset += $thisfile_asf_contentdescriptionobject['description_length']; $thisfile_asf_contentdescriptionobject['rating'] = substr($ASFHeaderData, $offset, $thisfile_asf_contentdescriptionobject['rating_length']); $offset += $thisfile_asf_contentdescriptionobject['rating_length']; $ASFcommentKeysToCopy = array('title'=>'title', 'author'=>'artist', 'copyright'=>'copyright', 'description'=>'comment', 'rating'=>'rating'); foreach ($ASFcommentKeysToCopy as $keytocopyfrom => $keytocopyto) { if (!empty($thisfile_asf_contentdescriptionobject[$keytocopyfrom])) { $thisfile_asf_comments[$keytocopyto][] = $this->TrimTerm($thisfile_asf_contentdescriptionobject[$keytocopyfrom]); } } break; case GETID3_ASF_Extended_Content_Description_Object: // Extended Content Description Object: (optional, one only) // Field Name Field Type Size (bits) // Object ID GUID 128 // GUID for Extended Content Description object - GETID3_ASF_Extended_Content_Description_Object // Object Size QWORD 64 // size of ExtendedContent Description object, including 26 bytes of Extended Content Description Object header // Content Descriptors Count WORD 16 // number of entries in Content Descriptors list // Content Descriptors array of: variable // // * Descriptor Name Length WORD 16 // size in bytes of Descriptor Name field // * Descriptor Name WCHAR variable // array of Unicode characters - Descriptor Name // * Descriptor Value Data Type WORD 16 // Lookup array: // 0x0000 = Unicode String (variable length) // 0x0001 = BYTE array (variable length) // 0x0002 = BOOL (DWORD, 32 bits) // 0x0003 = DWORD (DWORD, 32 bits) // 0x0004 = QWORD (QWORD, 64 bits) // 0x0005 = WORD (WORD, 16 bits) // * Descriptor Value Length WORD 16 // number of bytes stored in Descriptor Value field // * Descriptor Value variable variable // value for Content Descriptor // shortcut $thisfile_asf['extended_content_description_object'] = array(); $thisfile_asf_extendedcontentdescriptionobject = &$thisfile_asf['extended_content_description_object']; $thisfile_asf_extendedcontentdescriptionobject['offset'] = $NextObjectOffset + $offset; $thisfile_asf_extendedcontentdescriptionobject['objectid'] = $NextObjectGUID; $thisfile_asf_extendedcontentdescriptionobject['objectid_guid'] = $NextObjectGUIDtext; $thisfile_asf_extendedcontentdescriptionobject['objectsize'] = $NextObjectSize; $thisfile_asf_extendedcontentdescriptionobject['content_descriptors_count'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2)); $offset += 2; for ($ExtendedContentDescriptorsCounter = 0; $ExtendedContentDescriptorsCounter < $thisfile_asf_extendedcontentdescriptionobject['content_descriptors_count']; $ExtendedContentDescriptorsCounter++) { // shortcut $thisfile_asf_extendedcontentdescriptionobject['content_descriptors'][$ExtendedContentDescriptorsCounter] = array(); $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current = &$thisfile_asf_extendedcontentdescriptionobject['content_descriptors'][$ExtendedContentDescriptorsCounter]; $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['base_offset'] = $offset + 30; $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['name_length'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2)); $offset += 2; $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['name'] = substr($ASFHeaderData, $offset, $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['name_length']); $offset += $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['name_length']; $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value_type'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2)); $offset += 2; $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value_length'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2)); $offset += 2; $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value'] = substr($ASFHeaderData, $offset, $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value_length']); $offset += $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value_length']; switch ($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value_type']) { case 0x0000: // Unicode string break; case 0x0001: // BYTE array // do nothing break; case 0x0002: // BOOL $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value'] = (bool) getid3_lib::LittleEndian2Int($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value']); break; case 0x0003: // DWORD case 0x0004: // QWORD case 0x0005: // WORD $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value'] = getid3_lib::LittleEndian2Int($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value']); break; default: $this->warning('extended_content_description.content_descriptors.'.$ExtendedContentDescriptorsCounter.'.value_type is invalid ('.$thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value_type'].')'); //return false; break; } switch ($this->TrimConvert(strtolower($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['name']))) { case 'wm/albumartist': case 'artist': // Note: not 'artist', that comes from 'author' tag $thisfile_asf_comments['albumartist'] = array($this->TrimTerm($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value'])); break; case 'wm/albumtitle': case 'album': $thisfile_asf_comments['album'] = array($this->TrimTerm($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value'])); break; case 'wm/genre': case 'genre': $thisfile_asf_comments['genre'] = array($this->TrimTerm($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value'])); break; case 'wm/partofset': $thisfile_asf_comments['partofset'] = array($this->TrimTerm($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value'])); break; case 'wm/tracknumber': case 'tracknumber': // be careful casting to int: casting unicode strings to int gives unexpected results (stops parsing at first non-numeric character) $thisfile_asf_comments['track_number'] = array($this->TrimTerm($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value'])); foreach ($thisfile_asf_comments['track_number'] as $key => $value) { if (preg_match('/^[0-9\x00]+$/', $value)) { $thisfile_asf_comments['track_number'][$key] = intval(str_replace("\x00", '', $value)); } } break; case 'wm/track': if (empty($thisfile_asf_comments['track_number'])) { $thisfile_asf_comments['track_number'] = array(1 + (int) $this->TrimConvert($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value'])); } break; case 'wm/year': case 'year': case 'date': $thisfile_asf_comments['year'] = array( $this->TrimTerm($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value'])); break; case 'wm/lyrics': case 'lyrics': $thisfile_asf_comments['lyrics'] = array($this->TrimTerm($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value'])); break; case 'isvbr': if ($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value']) { $thisfile_audio['bitrate_mode'] = 'vbr'; $thisfile_video['bitrate_mode'] = 'vbr'; } break; case 'id3': $this->getid3->include_module('tag.id3v2'); $getid3_id3v2 = new getid3_id3v2($this->getid3); $getid3_id3v2->AnalyzeString($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value']); unset($getid3_id3v2); if ($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value_length'] > 1024) { $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value'] = '<value too large to display>'; } break; case 'wm/encodingtime': $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['encoding_time_unix'] = $this->FILETIMEtoUNIXtime($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value']); $thisfile_asf_comments['encoding_time_unix'] = array($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['encoding_time_unix']); break; case 'wm/picture': $WMpicture = $this->ASF_WMpicture($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value']); foreach ($WMpicture as $key => $value) { $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current[$key] = $value; } unset($WMpicture); /* $wm_picture_offset = 0; $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['image_type_id'] = getid3_lib::LittleEndian2Int(substr($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value'], $wm_picture_offset, 1)); $wm_picture_offset += 1; $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['image_type'] = self::WMpictureTypeLookup($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['image_type_id']); $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['image_size'] = getid3_lib::LittleEndian2Int(substr($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value'], $wm_picture_offset, 4)); $wm_picture_offset += 4; $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['image_mime'] = ''; do { $next_byte_pair = substr($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value'], $wm_picture_offset, 2); $wm_picture_offset += 2; $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['image_mime'] .= $next_byte_pair; } while ($next_byte_pair !== "\x00\x00"); $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['image_description'] = ''; do { $next_byte_pair = substr($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value'], $wm_picture_offset, 2); $wm_picture_offset += 2; $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['image_description'] .= $next_byte_pair; } while ($next_byte_pair !== "\x00\x00"); $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['dataoffset'] = $wm_picture_offset; $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['data'] = substr($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value'], $wm_picture_offset); unset($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value']); $imageinfo = array(); $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['image_mime'] = ''; $imagechunkcheck = getid3_lib::GetDataImageSize($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['data'], $imageinfo); unset($imageinfo); if (!empty($imagechunkcheck)) { $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['image_mime'] = image_type_to_mime_type($imagechunkcheck[2]); } if (!isset($thisfile_asf_comments['picture'])) { $thisfile_asf_comments['picture'] = array(); } $thisfile_asf_comments['picture'][] = array('data'=>$thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['data'], 'image_mime'=>$thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['image_mime']); */ break; default: switch ($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value_type']) { case 0: // Unicode string if (substr($this->TrimConvert($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['name']), 0, 3) == 'WM/') { $thisfile_asf_comments[str_replace('wm/', '', strtolower($this->TrimConvert($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['name'])))] = array($this->TrimTerm($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value'])); } break; case 1: break; } break; } } break; case GETID3_ASF_Stream_Bitrate_Properties_Object: // Stream Bitrate Properties Object: (optional, one only) // Field Name Field Type Size (bits) // Object ID GUID 128 // GUID for Stream Bitrate Properties object - GETID3_ASF_Stream_Bitrate_Properties_Object // Object Size QWORD 64 // size of Extended Content Description object, including 26 bytes of Stream Bitrate Properties Object header // Bitrate Records Count WORD 16 // number of records in Bitrate Records // Bitrate Records array of: variable // // * Flags WORD 16 // // * * Stream Number bits 7 (0x007F) // number of this stream // * * Reserved bits 9 (0xFF80) // hardcoded: 0 // * Average Bitrate DWORD 32 // in bits per second // shortcut $thisfile_asf['stream_bitrate_properties_object'] = array(); $thisfile_asf_streambitratepropertiesobject = &$thisfile_asf['stream_bitrate_properties_object']; $thisfile_asf_streambitratepropertiesobject['offset'] = $NextObjectOffset + $offset; $thisfile_asf_streambitratepropertiesobject['objectid'] = $NextObjectGUID; $thisfile_asf_streambitratepropertiesobject['objectid_guid'] = $NextObjectGUIDtext; $thisfile_asf_streambitratepropertiesobject['objectsize'] = $NextObjectSize; $thisfile_asf_streambitratepropertiesobject['bitrate_records_count'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2)); $offset += 2; for ($BitrateRecordsCounter = 0; $BitrateRecordsCounter < $thisfile_asf_streambitratepropertiesobject['bitrate_records_count']; $BitrateRecordsCounter++) { $thisfile_asf_streambitratepropertiesobject['bitrate_records'][$BitrateRecordsCounter]['flags_raw'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 2)); $offset += 2; $thisfile_asf_streambitratepropertiesobject['bitrate_records'][$BitrateRecordsCounter]['flags']['stream_number'] = $thisfile_asf_streambitratepropertiesobject['bitrate_records'][$BitrateRecordsCounter]['flags_raw'] & 0x007F; $thisfile_asf_streambitratepropertiesobject['bitrate_records'][$BitrateRecordsCounter]['bitrate'] = getid3_lib::LittleEndian2Int(substr($ASFHeaderData, $offset, 4)); $offset += 4; } break; case GETID3_ASF_Padding_Object: // Padding Object: (optional) // Field Name Field Type Size (bits) // Object ID GUID 128 // GUID for Padding object - GETID3_ASF_Padding_Object // Object Size QWORD 64 // size of Padding object, including 24 bytes of ASF Padding Object header // Padding Data BYTESTREAM variable // ignore // shortcut $thisfile_asf['padding_object'] = array(); $thisfile_asf_paddingobject = &$thisfile_asf['padding_object']; $thisfile_asf_paddingobject['offset'] = $NextObjectOffset + $offset; $thisfile_asf_paddingobject['objectid'] = $NextObjectGUID; $thisfile_asf_paddingobject['objectid_guid'] = $NextObjectGUIDtext; $thisfile_asf_paddingobject['objectsize'] = $NextObjectSize; $thisfile_asf_paddingobject['padding_length'] = $thisfile_asf_paddingobject['objectsize'] - 16 - 8; $thisfile_asf_paddingobject['padding'] = substr($ASFHeaderData, $offset, $thisfile_asf_paddingobject['padding_length']); $offset += ($NextObjectSize - 16 - 8); break; case GETID3_ASF_Extended_Content_Encryption_Object: case GETID3_ASF_Content_Encryption_Object: // WMA DRM - just ignore $offset += ($NextObjectSize - 16 - 8); break; default: // Implementations shall ignore any standard or non-standard object that they do not know how to handle. if ($this->GUIDname($NextObjectGUIDtext)) { $this->warning('unhandled GUID "'.$this->GUIDname($NextObjectGUIDtext).'" {'.$NextObjectGUIDtext.'} in ASF header at offset '.($offset - 16 - 8)); } else { $this->warning('unknown GUID {'.$NextObjectGUIDtext.'} in ASF header at offset '.($offset - 16 - 8)); } $offset += ($NextObjectSize - 16 - 8); break; } } if (isset($thisfile_asf_streambitratepropertiesobject['bitrate_records_count'])) { $ASFbitrateAudio = 0; $ASFbitrateVideo = 0; for ($BitrateRecordsCounter = 0; $BitrateRecordsCounter < $thisfile_asf_streambitratepropertiesobject['bitrate_records_count']; $BitrateRecordsCounter++) { if (isset($thisfile_asf_codeclistobject['codec_entries'][$BitrateRecordsCounter])) { switch ($thisfile_asf_codeclistobject['codec_entries'][$BitrateRecordsCounter]['type_raw']) { case 1: $ASFbitrateVideo += $thisfile_asf_streambitratepropertiesobject['bitrate_records'][$BitrateRecordsCounter]['bitrate']; break; case 2: $ASFbitrateAudio += $thisfile_asf_streambitratepropertiesobject['bitrate_records'][$BitrateRecordsCounter]['bitrate']; break; default: // do nothing break; } } } if ($ASFbitrateAudio > 0) { $thisfile_audio['bitrate'] = $ASFbitrateAudio; } if ($ASFbitrateVideo > 0) { $thisfile_video['bitrate'] = $ASFbitrateVideo; } } if (isset($thisfile_asf['stream_properties_object']) && is_array($thisfile_asf['stream_properties_object'])) { $thisfile_audio['bitrate'] = 0; $thisfile_video['bitrate'] = 0; foreach ($thisfile_asf['stream_properties_object'] as $streamnumber => $streamdata) { switch ($streamdata['stream_type']) { case GETID3_ASF_Audio_Media: // Field Name Field Type Size (bits) // Codec ID / Format Tag WORD 16 // unique ID of audio codec - defined as wFormatTag field of WAVEFORMATEX structure // Number of Channels WORD 16 // number of channels of audio - defined as nChannels field of WAVEFORMATEX structure // Samples Per Second DWORD 32 // in Hertz - defined as nSamplesPerSec field of WAVEFORMATEX structure // Average number of Bytes/sec DWORD 32 // bytes/sec of audio stream - defined as nAvgBytesPerSec field of WAVEFORMATEX structure // Block Alignment WORD 16 // block size in bytes of audio codec - defined as nBlockAlign field of WAVEFORMATEX structure // Bits per sample WORD 16 // bits per sample of mono data. set to zero for variable bitrate codecs. defined as wBitsPerSample field of WAVEFORMATEX structure // Codec Specific Data Size WORD 16 // size in bytes of Codec Specific Data buffer - defined as cbSize field of WAVEFORMATEX structure // Codec Specific Data BYTESTREAM variable // array of codec-specific data bytes // shortcut $thisfile_asf['audio_media'][$streamnumber] = array(); $thisfile_asf_audiomedia_currentstream = &$thisfile_asf['audio_media'][$streamnumber]; $audiomediaoffset = 0; $thisfile_asf_audiomedia_currentstream = getid3_riff::parseWAVEFORMATex(substr($streamdata['type_specific_data'], $audiomediaoffset, 16)); $audiomediaoffset += 16; $thisfile_audio['lossless'] = false; switch ($thisfile_asf_audiomedia_currentstream['raw']['wFormatTag']) { case 0x0001: // PCM case 0x0163: // WMA9 Lossless $thisfile_audio['lossless'] = true; break; } if (!empty($thisfile_asf['stream_bitrate_properties_object']['bitrate_records'])) { // @phpstan-ignore-line foreach ($thisfile_asf['stream_bitrate_properties_object']['bitrate_records'] as $dummy => $dataarray) { if (isset($dataarray['flags']['stream_number']) && ($dataarray['flags']['stream_number'] == $streamnumber)) { $thisfile_asf_audiomedia_currentstream['bitrate'] = $dataarray['bitrate']; $thisfile_audio['bitrate'] += $dataarray['bitrate']; break; } } } else { if (!empty($thisfile_asf_audiomedia_currentstream['bytes_sec'])) { $thisfile_audio['bitrate'] += $thisfile_asf_audiomedia_currentstream['bytes_sec'] * 8; } elseif (!empty($thisfile_asf_audiomedia_currentstream['bitrate'])) { $thisfile_audio['bitrate'] += $thisfile_asf_audiomedia_currentstream['bitrate']; } } $thisfile_audio['streams'][$streamnumber] = $thisfile_asf_audiomedia_currentstream; $thisfile_audio['streams'][$streamnumber]['wformattag'] = $thisfile_asf_audiomedia_currentstream['raw']['wFormatTag']; $thisfile_audio['streams'][$streamnumber]['lossless'] = $thisfile_audio['lossless']; $thisfile_audio['streams'][$streamnumber]['bitrate'] = $thisfile_audio['bitrate']; $thisfile_audio['streams'][$streamnumber]['dataformat'] = 'wma'; unset($thisfile_audio['streams'][$streamnumber]['raw']); $thisfile_asf_audiomedia_currentstream['codec_data_size'] = getid3_lib::LittleEndian2Int(substr($streamdata['type_specific_data'], $audiomediaoffset, 2)); $audiomediaoffset += 2; $thisfile_asf_audiomedia_currentstream['codec_data'] = substr($streamdata['type_specific_data'], $audiomediaoffset, $thisfile_asf_audiomedia_currentstream['codec_data_size']); $audiomediaoffset += $thisfile_asf_audiomedia_currentstream['codec_data_size']; break; case GETID3_ASF_Video_Media: // Field Name Field Type Size (bits) // Encoded Image Width DWORD 32 // width of image in pixels // Encoded Image Height DWORD 32 // height of image in pixels // Reserved Flags BYTE 8 // hardcoded: 0x02 // Format Data Size WORD 16 // size of Format Data field in bytes // Format Data array of: variable // // * Format Data Size DWORD 32 // number of bytes in Format Data field, in bytes - defined as biSize field of BITMAPINFOHEADER structure // * Image Width LONG 32 // width of encoded image in pixels - defined as biWidth field of BITMAPINFOHEADER structure // * Image Height LONG 32 // height of encoded image in pixels - defined as biHeight field of BITMAPINFOHEADER structure // * Reserved WORD 16 // hardcoded: 0x0001 - defined as biPlanes field of BITMAPINFOHEADER structure // * Bits Per Pixel Count WORD 16 // bits per pixel - defined as biBitCount field of BITMAPINFOHEADER structure // * Compression ID FOURCC 32 // fourcc of video codec - defined as biCompression field of BITMAPINFOHEADER structure // * Image Size DWORD 32 // image size in bytes - defined as biSizeImage field of BITMAPINFOHEADER structure // * Horizontal Pixels / Meter DWORD 32 // horizontal resolution of target device in pixels per meter - defined as biXPelsPerMeter field of BITMAPINFOHEADER structure // * Vertical Pixels / Meter DWORD 32 // vertical resolution of target device in pixels per meter - defined as biYPelsPerMeter field of BITMAPINFOHEADER structure // * Colors Used Count DWORD 32 // number of color indexes in the color table that are actually used - defined as biClrUsed field of BITMAPINFOHEADER structure // * Important Colors Count DWORD 32 // number of color index required for displaying bitmap. if zero, all colors are required. defined as biClrImportant field of BITMAPINFOHEADER structure // * Codec Specific Data BYTESTREAM variable // array of codec-specific data bytes // shortcut $thisfile_asf['video_media'][$streamnumber] = array(); $thisfile_asf_videomedia_currentstream = &$thisfile_asf['video_media'][$streamnumber]; $videomediaoffset = 0; $thisfile_asf_videomedia_currentstream['image_width'] = getid3_lib::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 4)); $videomediaoffset += 4; $thisfile_asf_videomedia_currentstream['image_height'] = getid3_lib::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 4)); $videomediaoffset += 4; $thisfile_asf_videomedia_currentstream['flags'] = getid3_lib::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 1)); $videomediaoffset += 1; $thisfile_asf_videomedia_currentstream['format_data_size'] = getid3_lib::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 2)); $videomediaoffset += 2; $thisfile_asf_videomedia_currentstream['format_data']['format_data_size'] = getid3_lib::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 4)); $videomediaoffset += 4; $thisfile_asf_videomedia_currentstream['format_data']['image_width'] = getid3_lib::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 4)); $videomediaoffset += 4; $thisfile_asf_videomedia_currentstream['format_data']['image_height'] = getid3_lib::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 4)); $videomediaoffset += 4; $thisfile_asf_videomedia_currentstream['format_data']['reserved'] = getid3_lib::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 2)); $videomediaoffset += 2; $thisfile_asf_videomedia_currentstream['format_data']['bits_per_pixel'] = getid3_lib::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 2)); $videomediaoffset += 2; $thisfile_asf_videomedia_currentstream['format_data']['codec_fourcc'] = substr($streamdata['type_specific_data'], $videomediaoffset, 4); $videomediaoffset += 4; $thisfile_asf_videomedia_currentstream['format_data']['image_size'] = getid3_lib::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 4)); $videomediaoffset += 4; $thisfile_asf_videomedia_currentstream['format_data']['horizontal_pels'] = getid3_lib::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 4)); $videomediaoffset += 4; $thisfile_asf_videomedia_currentstream['format_data']['vertical_pels'] = getid3_lib::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 4)); $videomediaoffset += 4; $thisfile_asf_videomedia_currentstream['format_data']['colors_used'] = getid3_lib::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 4)); $videomediaoffset += 4; $thisfile_asf_videomedia_currentstream['format_data']['colors_important'] = getid3_lib::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 4)); $videomediaoffset += 4; $thisfile_asf_videomedia_currentstream['format_data']['codec_data'] = substr($streamdata['type_specific_data'], $videomediaoffset); if (!empty($thisfile_asf['stream_bitrate_properties_object']['bitrate_records'])) { // @phpstan-ignore-line foreach ($thisfile_asf['stream_bitrate_properties_object']['bitrate_records'] as $dummy => $dataarray) { if (isset($dataarray['flags']['stream_number']) && ($dataarray['flags']['stream_number'] == $streamnumber)) { $thisfile_asf_videomedia_currentstream['bitrate'] = $dataarray['bitrate']; $thisfile_video['streams'][$streamnumber]['bitrate'] = $dataarray['bitrate']; $thisfile_video['bitrate'] += $dataarray['bitrate']; break; } } } $thisfile_asf_videomedia_currentstream['format_data']['codec'] = getid3_riff::fourccLookup($thisfile_asf_videomedia_currentstream['format_data']['codec_fourcc']); $thisfile_video['streams'][$streamnumber]['fourcc'] = $thisfile_asf_videomedia_currentstream['format_data']['codec_fourcc']; $thisfile_video['streams'][$streamnumber]['codec'] = $thisfile_asf_videomedia_currentstream['format_data']['codec']; $thisfile_video['streams'][$streamnumber]['resolution_x'] = $thisfile_asf_videomedia_currentstream['image_width']; $thisfile_video['streams'][$streamnumber]['resolution_y'] = $thisfile_asf_videomedia_currentstream['image_height']; $thisfile_video['streams'][$streamnumber]['bits_per_sample'] = $thisfile_asf_videomedia_currentstream['format_data']['bits_per_pixel']; break; default: break; } } } while ($this->ftell() < $info['avdataend']) { $NextObjectDataHeader = $this->fread(24); $offset = 0; $NextObjectGUID = substr($NextObjectDataHeader, 0, 16); $offset += 16; $NextObjectGUIDtext = $this->BytestringToGUID($NextObjectGUID); $NextObjectSize = getid3_lib::LittleEndian2Int(substr($NextObjectDataHeader, $offset, 8)); $offset += 8; switch ($NextObjectGUID) { case GETID3_ASF_Data_Object: // Data Object: (mandatory, one only) // Field Name Field Type Size (bits) // Object ID GUID 128 // GUID for Data object - GETID3_ASF_Data_Object // Object Size QWORD 64 // size of Data object, including 50 bytes of Data Object header. may be 0 if FilePropertiesObject.BroadcastFlag == 1 // File ID GUID 128 // unique identifier. identical to File ID field in Header Object // Total Data Packets QWORD 64 // number of Data Packet entries in Data Object. invalid if FilePropertiesObject.BroadcastFlag == 1 // Reserved WORD 16 // hardcoded: 0x0101 // shortcut $thisfile_asf['data_object'] = array(); $thisfile_asf_dataobject = &$thisfile_asf['data_object']; $DataObjectData = $NextObjectDataHeader.$this->fread(50 - 24); $offset = 24; $thisfile_asf_dataobject['objectid'] = $NextObjectGUID; $thisfile_asf_dataobject['objectid_guid'] = $NextObjectGUIDtext; $thisfile_asf_dataobject['objectsize'] = $NextObjectSize; $thisfile_asf_dataobject['fileid'] = substr($DataObjectData, $offset, 16); $offset += 16; $thisfile_asf_dataobject['fileid_guid'] = $this->BytestringToGUID($thisfile_asf_dataobject['fileid']); $thisfile_asf_dataobject['total_data_packets'] = getid3_lib::LittleEndian2Int(substr($DataObjectData, $offset, 8)); $offset += 8; $thisfile_asf_dataobject['reserved'] = getid3_lib::LittleEndian2Int(substr($DataObjectData, $offset, 2)); $offset += 2; if ($thisfile_asf_dataobject['reserved'] != 0x0101) { $this->warning('data_object.reserved (0x'.sprintf('%04X', $thisfile_asf_dataobject['reserved']).') does not match expected value of "0x0101"'); //return false; break; } // Data Packets array of: variable // // * Error Correction Flags BYTE 8 // // * * Error Correction Data Length bits 4 // if Error Correction Length Type == 00, size of Error Correction Data in bytes, else hardcoded: 0000 // * * Opaque Data Present bits 1 // // * * Error Correction Length Type bits 2 // number of bits for size of the error correction data. hardcoded: 00 // * * Error Correction Present bits 1 // If set, use Opaque Data Packet structure, else use Payload structure // * Error Correction Data $info['avdataoffset'] = $this->ftell(); $this->fseek(($thisfile_asf_dataobject['objectsize'] - 50), SEEK_CUR); // skip actual audio/video data $info['avdataend'] = $this->ftell(); break; case GETID3_ASF_Simple_Index_Object: // Simple Index Object: (optional, recommended, one per video stream) // Field Name Field Type Size (bits) // Object ID GUID 128 // GUID for Simple Index object - GETID3_ASF_Data_Object // Object Size QWORD 64 // size of Simple Index object, including 56 bytes of Simple Index Object header // File ID GUID 128 // unique identifier. may be zero or identical to File ID field in Data Object and Header Object // Index Entry Time Interval QWORD 64 // interval between index entries in 100-nanosecond units // Maximum Packet Count DWORD 32 // maximum packet count for all index entries // Index Entries Count DWORD 32 // number of Index Entries structures // Index Entries array of: variable // // * Packet Number DWORD 32 // number of the Data Packet associated with this index entry // * Packet Count WORD 16 // number of Data Packets to sent at this index entry // shortcut $thisfile_asf['simple_index_object'] = array(); $thisfile_asf_simpleindexobject = &$thisfile_asf['simple_index_object']; $SimpleIndexObjectData = $NextObjectDataHeader.$this->fread(56 - 24); $offset = 24; $thisfile_asf_simpleindexobject['objectid'] = $NextObjectGUID; $thisfile_asf_simpleindexobject['objectid_guid'] = $NextObjectGUIDtext; $thisfile_asf_simpleindexobject['objectsize'] = $NextObjectSize; $thisfile_asf_simpleindexobject['fileid'] = substr($SimpleIndexObjectData, $offset, 16); $offset += 16; $thisfile_asf_simpleindexobject['fileid_guid'] = $this->BytestringToGUID($thisfile_asf_simpleindexobject['fileid']); $thisfile_asf_simpleindexobject['index_entry_time_interval'] = getid3_lib::LittleEndian2Int(substr($SimpleIndexObjectData, $offset, 8)); $offset += 8; $thisfile_asf_simpleindexobject['maximum_packet_count'] = getid3_lib::LittleEndian2Int(substr($SimpleIndexObjectData, $offset, 4)); $offset += 4; $thisfile_asf_simpleindexobject['index_entries_count'] = getid3_lib::LittleEndian2Int(substr($SimpleIndexObjectData, $offset, 4)); $offset += 4; $IndexEntriesData = $SimpleIndexObjectData.$this->fread(6 * $thisfile_asf_simpleindexobject['index_entries_count']); for ($IndexEntriesCounter = 0; $IndexEntriesCounter < $thisfile_asf_simpleindexobject['index_entries_count']; $IndexEntriesCounter++) { $thisfile_asf_simpleindexobject['index_entries'][$IndexEntriesCounter]['packet_number'] = getid3_lib::LittleEndian2Int(substr($IndexEntriesData, $offset, 4)); $offset += 4; $thisfile_asf_simpleindexobject['index_entries'][$IndexEntriesCounter]['packet_count'] = getid3_lib::LittleEndian2Int(substr($IndexEntriesData, $offset, 4)); $offset += 2; } break; case GETID3_ASF_Index_Object: // 6.2 ASF top-level Index Object (optional but recommended when appropriate, 0 or 1) // Field Name Field Type Size (bits) // Object ID GUID 128 // GUID for the Index Object - GETID3_ASF_Index_Object // Object Size QWORD 64 // Specifies the size, in bytes, of the Index Object, including at least 34 bytes of Index Object header // Index Entry Time Interval DWORD 32 // Specifies the time interval between each index entry in ms. // Index Specifiers Count WORD 16 // Specifies the number of Index Specifiers structures in this Index Object. // Index Blocks Count DWORD 32 // Specifies the number of Index Blocks structures in this Index Object. // Index Entry Time Interval DWORD 32 // Specifies the time interval between index entries in milliseconds. This value cannot be 0. // Index Specifiers Count WORD 16 // Specifies the number of entries in the Index Specifiers list. Valid values are 1 and greater. // Index Specifiers array of: varies // // * Stream Number WORD 16 // Specifies the stream number that the Index Specifiers refer to. Valid values are between 1 and 127. // * Index Type WORD 16 // Specifies Index Type values as follows: // 1 = Nearest Past Data Packet - indexes point to the data packet whose presentation time is closest to the index entry time. // 2 = Nearest Past Media Object - indexes point to the closest data packet containing an entire object or first fragment of an object. // 3 = Nearest Past Cleanpoint. - indexes point to the closest data packet containing an entire object (or first fragment of an object) that has the Cleanpoint Flag set. // Nearest Past Cleanpoint is the most common type of index. // Index Entry Count DWORD 32 // Specifies the number of Index Entries in the block. // * Block Positions QWORD varies // Specifies a list of byte offsets of the beginnings of the blocks relative to the beginning of the first Data Packet (i.e., the beginning of the Data Object + 50 bytes). The number of entries in this list is specified by the value of the Index Specifiers Count field. The order of those byte offsets is tied to the order in which Index Specifiers are listed. // * Index Entries array of: varies // // * * Offsets DWORD varies // An offset value of 0xffffffff indicates an invalid offset value // shortcut $thisfile_asf['asf_index_object'] = array(); $thisfile_asf_asfindexobject = &$thisfile_asf['asf_index_object']; $ASFIndexObjectData = $NextObjectDataHeader.$this->fread(34 - 24); $offset = 24; $thisfile_asf_asfindexobject['objectid'] = $NextObjectGUID; $thisfile_asf_asfindexobject['objectid_guid'] = $NextObjectGUIDtext; $thisfile_asf_asfindexobject['objectsize'] = $NextObjectSize; $thisfile_asf_asfindexobject['entry_time_interval'] = getid3_lib::LittleEndian2Int(substr($ASFIndexObjectData, $offset, 4)); $offset += 4; $thisfile_asf_asfindexobject['index_specifiers_count'] = getid3_lib::LittleEndian2Int(substr($ASFIndexObjectData, $offset, 2)); $offset += 2; $thisfile_asf_asfindexobject['index_blocks_count'] = getid3_lib::LittleEndian2Int(substr($ASFIndexObjectData, $offset, 4)); $offset += 4; $ASFIndexObjectData .= $this->fread(4 * $thisfile_asf_asfindexobject['index_specifiers_count']); for ($IndexSpecifiersCounter = 0; $IndexSpecifiersCounter < $thisfile_asf_asfindexobject['index_specifiers_count']; $IndexSpecifiersCounter++) { $IndexSpecifierStreamNumber = getid3_lib::LittleEndian2Int(substr($ASFIndexObjectData, $offset, 2)); $offset += 2; $thisfile_asf_asfindexobject['index_specifiers'][$IndexSpecifiersCounter]['stream_number'] = $IndexSpecifierStreamNumber; $thisfile_asf_asfindexobject['index_specifiers'][$IndexSpecifiersCounter]['index_type'] = getid3_lib::LittleEndian2Int(substr($ASFIndexObjectData, $offset, 2)); $offset += 2; $thisfile_asf_asfindexobject['index_specifiers'][$IndexSpecifiersCounter]['index_type_text'] = $this->ASFIndexObjectIndexTypeLookup($thisfile_asf_asfindexobject['index_specifiers'][$IndexSpecifiersCounter]['index_type']); } $ASFIndexObjectData .= $this->fread(4); $thisfile_asf_asfindexobject['index_entry_count'] = getid3_lib::LittleEndian2Int(substr($ASFIndexObjectData, $offset, 4)); $offset += 4; $ASFIndexObjectData .= $this->fread(8 * $thisfile_asf_asfindexobject['index_specifiers_count']); for ($IndexSpecifiersCounter = 0; $IndexSpecifiersCounter < $thisfile_asf_asfindexobject['index_specifiers_count']; $IndexSpecifiersCounter++) { $thisfile_asf_asfindexobject['block_positions'][$IndexSpecifiersCounter] = getid3_lib::LittleEndian2Int(substr($ASFIndexObjectData, $offset, 8)); $offset += 8; } $ASFIndexObjectData .= $this->fread(4 * $thisfile_asf_asfindexobject['index_specifiers_count'] * $thisfile_asf_asfindexobject['index_entry_count']); for ($IndexEntryCounter = 0; $IndexEntryCounter < $thisfile_asf_asfindexobject['index_entry_count']; $IndexEntryCounter++) { for ($IndexSpecifiersCounter = 0; $IndexSpecifiersCounter < $thisfile_asf_asfindexobject['index_specifiers_count']; $IndexSpecifiersCounter++) { $thisfile_asf_asfindexobject['offsets'][$IndexSpecifiersCounter][$IndexEntryCounter] = getid3_lib::LittleEndian2Int(substr($ASFIndexObjectData, $offset, 4)); $offset += 4; } } break; default: // Implementations shall ignore any standard or non-standard object that they do not know how to handle. if ($this->GUIDname($NextObjectGUIDtext)) { $this->warning('unhandled GUID "'.$this->GUIDname($NextObjectGUIDtext).'" {'.$NextObjectGUIDtext.'} in ASF body at offset '.($offset - 16 - 8)); } else { $this->warning('unknown GUID {'.$NextObjectGUIDtext.'} in ASF body at offset '.($this->ftell() - 16 - 8)); } $this->fseek(($NextObjectSize - 16 - 8), SEEK_CUR); break; } } if (isset($thisfile_asf_codeclistobject['codec_entries']) && is_array($thisfile_asf_codeclistobject['codec_entries'])) { foreach ($thisfile_asf_codeclistobject['codec_entries'] as $streamnumber => $streamdata) { switch ($streamdata['information']) { case 'WMV1': case 'WMV2': case 'WMV3': case 'MSS1': case 'MSS2': case 'WMVA': case 'WVC1': case 'WMVP': case 'WVP2': $thisfile_video['dataformat'] = 'wmv'; $info['mime_type'] = 'video/x-ms-wmv'; break; case 'MP42': case 'MP43': case 'MP4S': case 'mp4s': $thisfile_video['dataformat'] = 'asf'; $info['mime_type'] = 'video/x-ms-asf'; break; default: switch ($streamdata['type_raw']) { case 1: if (strstr($this->TrimConvert($streamdata['name']), 'Windows Media')) { $thisfile_video['dataformat'] = 'wmv'; if ($info['mime_type'] == 'video/x-ms-asf') { $info['mime_type'] = 'video/x-ms-wmv'; } } break; case 2: if (strstr($this->TrimConvert($streamdata['name']), 'Windows Media')) { $thisfile_audio['dataformat'] = 'wma'; if ($info['mime_type'] == 'video/x-ms-asf') { $info['mime_type'] = 'audio/x-ms-wma'; } } break; } break; } } } switch (isset($thisfile_audio['codec']) ? $thisfile_audio['codec'] : '') { case 'MPEG Layer-3': $thisfile_audio['dataformat'] = 'mp3'; break; default: break; } if (isset($thisfile_asf_codeclistobject['codec_entries'])) { foreach ($thisfile_asf_codeclistobject['codec_entries'] as $streamnumber => $streamdata) { switch ($streamdata['type_raw']) { case 1: // video $thisfile_video['encoder'] = $this->TrimConvert($thisfile_asf_codeclistobject['codec_entries'][$streamnumber]['name']); break; case 2: // audio $thisfile_audio['encoder'] = $this->TrimConvert($thisfile_asf_codeclistobject['codec_entries'][$streamnumber]['name']); // AH 2003-10-01 $thisfile_audio['encoder_options'] = $this->TrimConvert($thisfile_asf_codeclistobject['codec_entries'][0]['description']); $thisfile_audio['codec'] = $thisfile_audio['encoder']; break; default: $this->warning('Unknown streamtype: [codec_list_object][codec_entries]['.$streamnumber.'][type_raw] == '.$streamdata['type_raw']); break; } } } if (isset($info['audio'])) { $thisfile_audio['lossless'] = (isset($thisfile_audio['lossless']) ? $thisfile_audio['lossless'] : false); $thisfile_audio['dataformat'] = (!empty($thisfile_audio['dataformat']) ? $thisfile_audio['dataformat'] : 'asf'); } if (!empty($thisfile_video['dataformat'])) { $thisfile_video['lossless'] = (isset($thisfile_audio['lossless']) ? $thisfile_audio['lossless'] : false); $thisfile_video['pixel_aspect_ratio'] = (isset($thisfile_audio['pixel_aspect_ratio']) ? $thisfile_audio['pixel_aspect_ratio'] : (float) 1); $thisfile_video['dataformat'] = (!empty($thisfile_video['dataformat']) ? $thisfile_video['dataformat'] : 'asf'); } if (!empty($thisfile_video['streams'])) { $thisfile_video['resolution_x'] = 0; $thisfile_video['resolution_y'] = 0; foreach ($thisfile_video['streams'] as $key => $valuearray) { if (($valuearray['resolution_x'] > $thisfile_video['resolution_x']) || ($valuearray['resolution_y'] > $thisfile_video['resolution_y'])) { $thisfile_video['resolution_x'] = $valuearray['resolution_x']; $thisfile_video['resolution_y'] = $valuearray['resolution_y']; } } } $info['bitrate'] = 0 + (isset($thisfile_audio['bitrate']) ? $thisfile_audio['bitrate'] : 0) + (isset($thisfile_video['bitrate']) ? $thisfile_video['bitrate'] : 0); if ((!isset($info['playtime_seconds']) || ($info['playtime_seconds'] <= 0)) && ($info['bitrate'] > 0)) { $info['playtime_seconds'] = ($info['filesize'] - $info['avdataoffset']) / ($info['bitrate'] / 8); } return true; } /** * @param int $CodecListType * * @return string */ public static function codecListObjectTypeLookup($CodecListType) { static $lookup = array( 0x0001 => 'Video Codec', 0x0002 => 'Audio Codec', 0xFFFF => 'Unknown Codec' ); return (isset($lookup[$CodecListType]) ? $lookup[$CodecListType] : 'Invalid Codec Type'); } /** * @return array */ public static function KnownGUIDs() { static $GUIDarray = array( 'GETID3_ASF_Extended_Stream_Properties_Object' => '14E6A5CB-C672-4332-8399-A96952065B5A', 'GETID3_ASF_Padding_Object' => '1806D474-CADF-4509-A4BA-9AABCB96AAE8', 'GETID3_ASF_Payload_Ext_Syst_Pixel_Aspect_Ratio' => '1B1EE554-F9EA-4BC8-821A-376B74E4C4B8', 'GETID3_ASF_Script_Command_Object' => '1EFB1A30-0B62-11D0-A39B-00A0C90348F6', 'GETID3_ASF_No_Error_Correction' => '20FB5700-5B55-11CF-A8FD-00805F5C442B', 'GETID3_ASF_Content_Branding_Object' => '2211B3FA-BD23-11D2-B4B7-00A0C955FC6E', 'GETID3_ASF_Content_Encryption_Object' => '2211B3FB-BD23-11D2-B4B7-00A0C955FC6E', 'GETID3_ASF_Digital_Signature_Object' => '2211B3FC-BD23-11D2-B4B7-00A0C955FC6E', 'GETID3_ASF_Extended_Content_Encryption_Object' => '298AE614-2622-4C17-B935-DAE07EE9289C', 'GETID3_ASF_Simple_Index_Object' => '33000890-E5B1-11CF-89F4-00A0C90349CB', 'GETID3_ASF_Degradable_JPEG_Media' => '35907DE0-E415-11CF-A917-00805F5C442B', 'GETID3_ASF_Payload_Extension_System_Timecode' => '399595EC-8667-4E2D-8FDB-98814CE76C1E', 'GETID3_ASF_Binary_Media' => '3AFB65E2-47EF-40F2-AC2C-70A90D71D343', 'GETID3_ASF_Timecode_Index_Object' => '3CB73FD0-0C4A-4803-953D-EDF7B6228F0C', 'GETID3_ASF_Metadata_Library_Object' => '44231C94-9498-49D1-A141-1D134E457054', 'GETID3_ASF_Reserved_3' => '4B1ACBE3-100B-11D0-A39B-00A0C90348F6', 'GETID3_ASF_Reserved_4' => '4CFEDB20-75F6-11CF-9C0F-00A0C90349CB', 'GETID3_ASF_Command_Media' => '59DACFC0-59E6-11D0-A3AC-00A0C90348F6', 'GETID3_ASF_Header_Extension_Object' => '5FBF03B5-A92E-11CF-8EE3-00C00C205365', 'GETID3_ASF_Media_Object_Index_Parameters_Obj' => '6B203BAD-3F11-4E84-ACA8-D7613DE2CFA7', 'GETID3_ASF_Header_Object' => '75B22630-668E-11CF-A6D9-00AA0062CE6C', 'GETID3_ASF_Content_Description_Object' => '75B22633-668E-11CF-A6D9-00AA0062CE6C', 'GETID3_ASF_Error_Correction_Object' => '75B22635-668E-11CF-A6D9-00AA0062CE6C', 'GETID3_ASF_Data_Object' => '75B22636-668E-11CF-A6D9-00AA0062CE6C', 'GETID3_ASF_Web_Stream_Media_Subtype' => '776257D4-C627-41CB-8F81-7AC7FF1C40CC', 'GETID3_ASF_Stream_Bitrate_Properties_Object' => '7BF875CE-468D-11D1-8D82-006097C9A2B2', 'GETID3_ASF_Language_List_Object' => '7C4346A9-EFE0-4BFC-B229-393EDE415C85', 'GETID3_ASF_Codec_List_Object' => '86D15240-311D-11D0-A3A4-00A0C90348F6', 'GETID3_ASF_Reserved_2' => '86D15241-311D-11D0-A3A4-00A0C90348F6', 'GETID3_ASF_File_Properties_Object' => '8CABDCA1-A947-11CF-8EE4-00C00C205365', 'GETID3_ASF_File_Transfer_Media' => '91BD222C-F21C-497A-8B6D-5AA86BFC0185', 'GETID3_ASF_Old_RTP_Extension_Data' => '96800C63-4C94-11D1-837B-0080C7A37F95', 'GETID3_ASF_Advanced_Mutual_Exclusion_Object' => 'A08649CF-4775-4670-8A16-6E35357566CD', 'GETID3_ASF_Bandwidth_Sharing_Object' => 'A69609E6-517B-11D2-B6AF-00C04FD908E9', 'GETID3_ASF_Reserved_1' => 'ABD3D211-A9BA-11cf-8EE6-00C00C205365', 'GETID3_ASF_Bandwidth_Sharing_Exclusive' => 'AF6060AA-5197-11D2-B6AF-00C04FD908E9', 'GETID3_ASF_Bandwidth_Sharing_Partial' => 'AF6060AB-5197-11D2-B6AF-00C04FD908E9', 'GETID3_ASF_JFIF_Media' => 'B61BE100-5B4E-11CF-A8FD-00805F5C442B', 'GETID3_ASF_Stream_Properties_Object' => 'B7DC0791-A9B7-11CF-8EE6-00C00C205365', 'GETID3_ASF_Video_Media' => 'BC19EFC0-5B4D-11CF-A8FD-00805F5C442B', 'GETID3_ASF_Audio_Spread' => 'BFC3CD50-618F-11CF-8BB2-00AA00B4E220', 'GETID3_ASF_Metadata_Object' => 'C5F8CBEA-5BAF-4877-8467-AA8C44FA4CCA', 'GETID3_ASF_Payload_Ext_Syst_Sample_Duration' => 'C6BD9450-867F-4907-83A3-C77921B733AD', 'GETID3_ASF_Group_Mutual_Exclusion_Object' => 'D1465A40-5A79-4338-B71B-E36B8FD6C249', 'GETID3_ASF_Extended_Content_Description_Object' => 'D2D0A440-E307-11D2-97F0-00A0C95EA850', 'GETID3_ASF_Stream_Prioritization_Object' => 'D4FED15B-88D3-454F-81F0-ED5C45999E24', 'GETID3_ASF_Payload_Ext_System_Content_Type' => 'D590DC20-07BC-436C-9CF7-F3BBFBF1A4DC', 'GETID3_ASF_Old_File_Properties_Object' => 'D6E229D0-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_ASF_Header_Object' => 'D6E229D1-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_ASF_Data_Object' => 'D6E229D2-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Index_Object' => 'D6E229D3-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_Stream_Properties_Object' => 'D6E229D4-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_Content_Description_Object' => 'D6E229D5-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_Script_Command_Object' => 'D6E229D6-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_Marker_Object' => 'D6E229D7-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_Component_Download_Object' => 'D6E229D8-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_Stream_Group_Object' => 'D6E229D9-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_Scalable_Object' => 'D6E229DA-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_Prioritization_Object' => 'D6E229DB-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Bitrate_Mutual_Exclusion_Object' => 'D6E229DC-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_Inter_Media_Dependency_Object' => 'D6E229DD-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_Rating_Object' => 'D6E229DE-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Index_Parameters_Object' => 'D6E229DF-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_Color_Table_Object' => 'D6E229E0-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_Language_List_Object' => 'D6E229E1-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_Audio_Media' => 'D6E229E2-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_Video_Media' => 'D6E229E3-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_Image_Media' => 'D6E229E4-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_Timecode_Media' => 'D6E229E5-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_Text_Media' => 'D6E229E6-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_MIDI_Media' => 'D6E229E7-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_Command_Media' => 'D6E229E8-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_No_Error_Concealment' => 'D6E229EA-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_Scrambled_Audio' => 'D6E229EB-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_No_Color_Table' => 'D6E229EC-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_SMPTE_Time' => 'D6E229ED-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_ASCII_Text' => 'D6E229EE-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_Unicode_Text' => 'D6E229EF-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_HTML_Text' => 'D6E229F0-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_URL_Command' => 'D6E229F1-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_Filename_Command' => 'D6E229F2-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_ACM_Codec' => 'D6E229F3-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_VCM_Codec' => 'D6E229F4-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_QuickTime_Codec' => 'D6E229F5-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_DirectShow_Transform_Filter' => 'D6E229F6-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_DirectShow_Rendering_Filter' => 'D6E229F7-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_No_Enhancement' => 'D6E229F8-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_Unknown_Enhancement_Type' => 'D6E229F9-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_Temporal_Enhancement' => 'D6E229FA-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_Spatial_Enhancement' => 'D6E229FB-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_Quality_Enhancement' => 'D6E229FC-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_Number_of_Channels_Enhancement' => 'D6E229FD-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_Frequency_Response_Enhancement' => 'D6E229FE-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_Media_Object' => 'D6E229FF-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Mutex_Language' => 'D6E22A00-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Mutex_Bitrate' => 'D6E22A01-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Mutex_Unknown' => 'D6E22A02-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_ASF_Placeholder_Object' => 'D6E22A0E-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Old_Data_Unit_Extension_Object' => 'D6E22A0F-35DA-11D1-9034-00A0C90349BE', 'GETID3_ASF_Web_Stream_Format' => 'DA1E6B13-8359-4050-B398-388E965BF00C', 'GETID3_ASF_Payload_Ext_System_File_Name' => 'E165EC0E-19ED-45D7-B4A7-25CBD1E28E9B', 'GETID3_ASF_Marker_Object' => 'F487CD01-A951-11CF-8EE6-00C00C205365', 'GETID3_ASF_Timecode_Index_Parameters_Object' => 'F55E496D-9797-4B5D-8C8B-604DFE9BFB24', 'GETID3_ASF_Audio_Media' => 'F8699E40-5B4D-11CF-A8FD-00805F5C442B', 'GETID3_ASF_Media_Object_Index_Object' => 'FEB103F8-12AD-4C64-840F-2A1D2F7AD48C', 'GETID3_ASF_Alt_Extended_Content_Encryption_Obj' => 'FF889EF1-ADEE-40DA-9E71-98704BB928CE', 'GETID3_ASF_Index_Placeholder_Object' => 'D9AADE20-7C17-4F9C-BC28-8555DD98E2A2', // https://metacpan.org/dist/Audio-WMA/source/WMA.pm 'GETID3_ASF_Compatibility_Object' => '26F18B5D-4584-47EC-9F5F-0E651F0452C9', // https://metacpan.org/dist/Audio-WMA/source/WMA.pm 'GETID3_ASF_Media_Object_Index_Parameters_Object'=> '6B203BAD-3F11-48E4-ACA8-D7613DE2CFA7', ); return $GUIDarray; } /** * @param string $GUIDstring * * @return string|false */ public static function GUIDname($GUIDstring) { static $GUIDarray = array(); if (empty($GUIDarray)) { $GUIDarray = self::KnownGUIDs(); } return array_search($GUIDstring, $GUIDarray); } /** * @param int $id * * @return string */ public static function ASFIndexObjectIndexTypeLookup($id) { static $ASFIndexObjectIndexTypeLookup = array(); if (empty($ASFIndexObjectIndexTypeLookup)) { $ASFIndexObjectIndexTypeLookup[1] = 'Nearest Past Data Packet'; $ASFIndexObjectIndexTypeLookup[2] = 'Nearest Past Media Object'; $ASFIndexObjectIndexTypeLookup[3] = 'Nearest Past Cleanpoint'; } return (isset($ASFIndexObjectIndexTypeLookup[$id]) ? $ASFIndexObjectIndexTypeLookup[$id] : 'invalid'); } /** * @param string $GUIDstring * * @return string */ public static function GUIDtoBytestring($GUIDstring) { // Microsoft defines these 16-byte (128-bit) GUIDs in the strangest way: // first 4 bytes are in little-endian order // next 2 bytes are appended in little-endian order // next 2 bytes are appended in little-endian order // next 2 bytes are appended in big-endian order // next 6 bytes are appended in big-endian order // AaBbCcDd-EeFf-GgHh-IiJj-KkLlMmNnOoPp is stored as this 16-byte string: // $Dd $Cc $Bb $Aa $Ff $Ee $Hh $Gg $Ii $Jj $Kk $Ll $Mm $Nn $Oo $Pp $hexbytecharstring = chr(hexdec(substr($GUIDstring, 6, 2))); $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 4, 2))); $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 2, 2))); $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 0, 2))); $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 11, 2))); $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 9, 2))); $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 16, 2))); $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 14, 2))); $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 19, 2))); $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 21, 2))); $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 24, 2))); $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 26, 2))); $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 28, 2))); $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 30, 2))); $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 32, 2))); $hexbytecharstring .= chr(hexdec(substr($GUIDstring, 34, 2))); return $hexbytecharstring; } /** * @param string $Bytestring * * @return string */ public static function BytestringToGUID($Bytestring) { $GUIDstring = str_pad(dechex(ord($Bytestring[3])), 2, '0', STR_PAD_LEFT); $GUIDstring .= str_pad(dechex(ord($Bytestring[2])), 2, '0', STR_PAD_LEFT); $GUIDstring .= str_pad(dechex(ord($Bytestring[1])), 2, '0', STR_PAD_LEFT); $GUIDstring .= str_pad(dechex(ord($Bytestring[0])), 2, '0', STR_PAD_LEFT); $GUIDstring .= '-'; $GUIDstring .= str_pad(dechex(ord($Bytestring[5])), 2, '0', STR_PAD_LEFT); $GUIDstring .= str_pad(dechex(ord($Bytestring[4])), 2, '0', STR_PAD_LEFT); $GUIDstring .= '-'; $GUIDstring .= str_pad(dechex(ord($Bytestring[7])), 2, '0', STR_PAD_LEFT); $GUIDstring .= str_pad(dechex(ord($Bytestring[6])), 2, '0', STR_PAD_LEFT); $GUIDstring .= '-'; $GUIDstring .= str_pad(dechex(ord($Bytestring[8])), 2, '0', STR_PAD_LEFT); $GUIDstring .= str_pad(dechex(ord($Bytestring[9])), 2, '0', STR_PAD_LEFT); $GUIDstring .= '-'; $GUIDstring .= str_pad(dechex(ord($Bytestring[10])), 2, '0', STR_PAD_LEFT); $GUIDstring .= str_pad(dechex(ord($Bytestring[11])), 2, '0', STR_PAD_LEFT); $GUIDstring .= str_pad(dechex(ord($Bytestring[12])), 2, '0', STR_PAD_LEFT); $GUIDstring .= str_pad(dechex(ord($Bytestring[13])), 2, '0', STR_PAD_LEFT); $GUIDstring .= str_pad(dechex(ord($Bytestring[14])), 2, '0', STR_PAD_LEFT); $GUIDstring .= str_pad(dechex(ord($Bytestring[15])), 2, '0', STR_PAD_LEFT); return strtoupper($GUIDstring); } /** * @param int $FILETIME * @param bool $round * * @return float|int */ public static function FILETIMEtoUNIXtime($FILETIME, $round=true) { // FILETIME is a 64-bit unsigned integer representing // the number of 100-nanosecond intervals since January 1, 1601 // UNIX timestamp is number of seconds since January 1, 1970 // 116444736000000000 = 10000000 * 60 * 60 * 24 * 365 * 369 + 89 leap days if ($round) { return intval(round(($FILETIME - 116444736000000000) / 10000000)); } return ($FILETIME - 116444736000000000) / 10000000; } /** * @param int $WMpictureType * * @return string */ public static function WMpictureTypeLookup($WMpictureType) { static $lookup = null; if ($lookup === null) { $lookup = array( 0x03 => 'Front Cover', 0x04 => 'Back Cover', 0x00 => 'User Defined', 0x05 => 'Leaflet Page', 0x06 => 'Media Label', 0x07 => 'Lead Artist', 0x08 => 'Artist', 0x09 => 'Conductor', 0x0A => 'Band', 0x0B => 'Composer', 0x0C => 'Lyricist', 0x0D => 'Recording Location', 0x0E => 'During Recording', 0x0F => 'During Performance', 0x10 => 'Video Screen Capture', 0x12 => 'Illustration', 0x13 => 'Band Logotype', 0x14 => 'Publisher Logotype' ); $lookup = array_map(function($str) { return getid3_lib::iconv_fallback('UTF-8', 'UTF-16LE', $str); }, $lookup); } return (isset($lookup[$WMpictureType]) ? $lookup[$WMpictureType] : ''); } /** * @param string $asf_header_extension_object_data * @param int $unhandled_sections * * @return array */ public function HeaderExtensionObjectDataParse(&$asf_header_extension_object_data, &$unhandled_sections) { // https://web.archive.org/web/20140419205228/http://msdn.microsoft.com/en-us/library/bb643323.aspx $offset = 0; $objectOffset = 0; $HeaderExtensionObjectParsed = array(); while ($objectOffset < strlen($asf_header_extension_object_data)) { $offset = $objectOffset; $thisObject = array(); $thisObject['guid'] = substr($asf_header_extension_object_data, $offset, 16); $offset += 16; $thisObject['guid_text'] = $this->BytestringToGUID($thisObject['guid']); $thisObject['guid_name'] = $this->GUIDname($thisObject['guid_text']); $thisObject['size'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 8)); $offset += 8; if ($thisObject['size'] <= 0) { break; } switch ($thisObject['guid']) { case GETID3_ASF_Extended_Stream_Properties_Object: $thisObject['start_time'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 8)); $offset += 8; $thisObject['start_time_unix'] = $this->FILETIMEtoUNIXtime($thisObject['start_time']); $thisObject['end_time'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 8)); $offset += 8; $thisObject['end_time_unix'] = $this->FILETIMEtoUNIXtime($thisObject['end_time']); $thisObject['data_bitrate'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 4)); $offset += 4; $thisObject['buffer_size'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 4)); $offset += 4; $thisObject['initial_buffer_fullness'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 4)); $offset += 4; $thisObject['alternate_data_bitrate'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 4)); $offset += 4; $thisObject['alternate_buffer_size'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 4)); $offset += 4; $thisObject['alternate_initial_buffer_fullness'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 4)); $offset += 4; $thisObject['maximum_object_size'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 4)); $offset += 4; $thisObject['flags_raw'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 4)); $offset += 4; $thisObject['flags']['reliable'] = (bool) $thisObject['flags_raw'] & 0x00000001; $thisObject['flags']['seekable'] = (bool) $thisObject['flags_raw'] & 0x00000002; $thisObject['flags']['no_cleanpoints'] = (bool) $thisObject['flags_raw'] & 0x00000004; $thisObject['flags']['resend_live_cleanpoints'] = (bool) $thisObject['flags_raw'] & 0x00000008; $thisObject['stream_number'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2)); $offset += 2; $thisObject['stream_language_id_index'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2)); $offset += 2; $thisObject['average_time_per_frame'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 8)); $offset += 8; $thisObject['stream_name_count'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2)); $offset += 2; $thisObject['payload_extension_system_count'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2)); $offset += 2; for ($i = 0; $i < $thisObject['stream_name_count']; $i++) { $streamName = array(); $streamName['language_id_index'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2)); $offset += 2; $streamName['stream_name_length'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2)); $offset += 2; $streamName['stream_name'] = substr($asf_header_extension_object_data, $offset, $streamName['stream_name_length']); $offset += $streamName['stream_name_length']; $thisObject['stream_names'][$i] = $streamName; } for ($i = 0; $i < $thisObject['payload_extension_system_count']; $i++) { $payloadExtensionSystem = array(); $payloadExtensionSystem['extension_system_id'] = substr($asf_header_extension_object_data, $offset, 16); $offset += 16; $payloadExtensionSystem['extension_system_id_text'] = $this->BytestringToGUID($payloadExtensionSystem['extension_system_id']); $payloadExtensionSystem['extension_system_size'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2)); $offset += 2; if ($payloadExtensionSystem['extension_system_size'] <= 0) { break 2; } $payloadExtensionSystem['extension_system_info_length'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 4)); $offset += 4; $payloadExtensionSystem['extension_system_info'] = substr($asf_header_extension_object_data, $offset, $payloadExtensionSystem['extension_system_info_length']); $offset += $payloadExtensionSystem['extension_system_info_length']; $thisObject['payload_extension_systems'][$i] = $payloadExtensionSystem; } break; case GETID3_ASF_Advanced_Mutual_Exclusion_Object: $thisObject['exclusion_type'] = substr($asf_header_extension_object_data, $offset, 16); $offset += 16; $thisObject['exclusion_type_text'] = $this->BytestringToGUID($thisObject['exclusion_type']); $thisObject['stream_numbers_count'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2)); $offset += 2; for ($i = 0; $i < $thisObject['stream_numbers_count']; $i++) { $thisObject['stream_numbers'][$i] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2)); $offset += 2; } break; case GETID3_ASF_Stream_Prioritization_Object: $thisObject['priority_records_count'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2)); $offset += 2; for ($i = 0; $i < $thisObject['priority_records_count']; $i++) { $priorityRecord = array(); $priorityRecord['stream_number'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2)); $offset += 2; $priorityRecord['flags_raw'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2)); $offset += 2; $priorityRecord['flags']['mandatory'] = (bool) $priorityRecord['flags_raw'] & 0x00000001; $thisObject['priority_records'][$i] = $priorityRecord; } break; case GETID3_ASF_Padding_Object: // padding, skip it break; case GETID3_ASF_Metadata_Object: $thisObject['description_record_counts'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2)); $offset += 2; for ($i = 0; $i < $thisObject['description_record_counts']; $i++) { $descriptionRecord = array(); $descriptionRecord['reserved_1'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2)); // must be zero $offset += 2; $descriptionRecord['stream_number'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2)); $offset += 2; $descriptionRecord['name_length'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2)); $offset += 2; $descriptionRecord['data_type'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2)); $offset += 2; $descriptionRecord['data_type_text'] = self::metadataLibraryObjectDataTypeLookup($descriptionRecord['data_type']); $descriptionRecord['data_length'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 4)); $offset += 4; $descriptionRecord['name'] = substr($asf_header_extension_object_data, $offset, $descriptionRecord['name_length']); $offset += $descriptionRecord['name_length']; $descriptionRecord['data'] = substr($asf_header_extension_object_data, $offset, $descriptionRecord['data_length']); $offset += $descriptionRecord['data_length']; switch ($descriptionRecord['data_type']) { case 0x0000: // Unicode string break; case 0x0001: // BYTE array // do nothing break; case 0x0002: // BOOL $descriptionRecord['data'] = (bool) getid3_lib::LittleEndian2Int($descriptionRecord['data']); break; case 0x0003: // DWORD case 0x0004: // QWORD case 0x0005: // WORD $descriptionRecord['data'] = getid3_lib::LittleEndian2Int($descriptionRecord['data']); break; case 0x0006: // GUID $descriptionRecord['data_text'] = $this->BytestringToGUID($descriptionRecord['data']); break; } $thisObject['description_record'][$i] = $descriptionRecord; } break; case GETID3_ASF_Language_List_Object: $thisObject['language_id_record_counts'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2)); $offset += 2; for ($i = 0; $i < $thisObject['language_id_record_counts']; $i++) { $languageIDrecord = array(); $languageIDrecord['language_id_length'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 1)); $offset += 1; $languageIDrecord['language_id'] = substr($asf_header_extension_object_data, $offset, $languageIDrecord['language_id_length']); $offset += $languageIDrecord['language_id_length']; $thisObject['language_id_record'][$i] = $languageIDrecord; } break; case GETID3_ASF_Metadata_Library_Object: $thisObject['description_records_count'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2)); $offset += 2; for ($i = 0; $i < $thisObject['description_records_count']; $i++) { $descriptionRecord = array(); $descriptionRecord['language_list_index'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2)); $offset += 2; $descriptionRecord['stream_number'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2)); $offset += 2; $descriptionRecord['name_length'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2)); $offset += 2; $descriptionRecord['data_type'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2)); $offset += 2; $descriptionRecord['data_type_text'] = self::metadataLibraryObjectDataTypeLookup($descriptionRecord['data_type']); $descriptionRecord['data_length'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 4)); $offset += 4; $descriptionRecord['name'] = substr($asf_header_extension_object_data, $offset, $descriptionRecord['name_length']); $offset += $descriptionRecord['name_length']; $descriptionRecord['data'] = substr($asf_header_extension_object_data, $offset, $descriptionRecord['data_length']); $offset += $descriptionRecord['data_length']; if (preg_match('#^WM/Picture$#', str_replace("\x00", '', trim($descriptionRecord['name'])))) { $WMpicture = $this->ASF_WMpicture($descriptionRecord['data']); foreach ($WMpicture as $key => $value) { $descriptionRecord['data'] = $WMpicture; } unset($WMpicture); } $thisObject['description_record'][$i] = $descriptionRecord; } break; case GETID3_ASF_Index_Parameters_Object: $thisObject['index_entry_time_interval'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 4)); $offset += 4; $thisObject['index_specifiers_count'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2)); $offset += 2; for ($i = 0; $i < $thisObject['index_specifiers_count']; $i++) { $indexSpecifier = array(); $indexSpecifier['stream_number'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2)); $offset += 2; $indexSpecifier['index_type'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2)); $offset += 2; $indexSpecifier['index_type_text'] = isset(static::$ASFIndexParametersObjectIndexSpecifiersIndexTypes[$indexSpecifier['index_type']]) ? static::$ASFIndexParametersObjectIndexSpecifiersIndexTypes[$indexSpecifier['index_type']] : 'invalid' ; $thisObject['index_specifiers'][$i] = $indexSpecifier; } break; case GETID3_ASF_Media_Object_Index_Parameters_Object: $thisObject['index_entry_count_interval'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 4)); $offset += 4; $thisObject['index_specifiers_count'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2)); $offset += 2; for ($i = 0; $i < $thisObject['index_specifiers_count']; $i++) { $indexSpecifier = array(); $indexSpecifier['stream_number'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2)); $offset += 2; $indexSpecifier['index_type'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2)); $offset += 2; $indexSpecifier['index_type_text'] = isset(static::$ASFMediaObjectIndexParametersObjectIndexSpecifiersIndexTypes[$indexSpecifier['index_type']]) ? static::$ASFMediaObjectIndexParametersObjectIndexSpecifiersIndexTypes[$indexSpecifier['index_type']] : 'invalid' ; $thisObject['index_specifiers'][$i] = $indexSpecifier; } break; case GETID3_ASF_Timecode_Index_Parameters_Object: // 4.11 Timecode Index Parameters Object (mandatory only if TIMECODE index is present in file, 0 or 1) // Field name Field type Size (bits) // Object ID GUID 128 // GUID for the Timecode Index Parameters Object - ASF_Timecode_Index_Parameters_Object // Object Size QWORD 64 // Specifies the size, in bytes, of the Timecode Index Parameters Object. Valid values are at least 34 bytes. // Index Entry Count Interval DWORD 32 // This value is ignored for the Timecode Index Parameters Object. // Index Specifiers Count WORD 16 // Specifies the number of entries in the Index Specifiers list. Valid values are 1 and greater. // Index Specifiers array of: varies // // * Stream Number WORD 16 // Specifies the stream number that the Index Specifiers refer to. Valid values are between 1 and 127. // * Index Type WORD 16 // Specifies the type of index. Values are defined as follows (1 is not a valid value): // 2 = Nearest Past Media Object - indexes point to the closest data packet containing an entire video frame or the first fragment of a video frame // 3 = Nearest Past Cleanpoint - indexes point to the closest data packet containing an entire video frame (or first fragment of a video frame) that is a key frame. // Nearest Past Media Object is the most common value $thisObject['index_entry_count_interval'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 4)); $offset += 4; $thisObject['index_specifiers_count'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2)); $offset += 2; for ($i = 0; $i < $thisObject['index_specifiers_count']; $i++) { $indexSpecifier = array(); $indexSpecifier['stream_number'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2)); $offset += 2; $indexSpecifier['index_type'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 2)); $offset += 2; $indexSpecifier['index_type_text'] = isset(static::$ASFTimecodeIndexParametersObjectIndexSpecifiersIndexTypes[$indexSpecifier['index_type']]) ? static::$ASFTimecodeIndexParametersObjectIndexSpecifiersIndexTypes[$indexSpecifier['index_type']] : 'invalid' ; $thisObject['index_specifiers'][$i] = $indexSpecifier; } break; case GETID3_ASF_Compatibility_Object: $thisObject['profile'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 1)); $offset += 1; $thisObject['mode'] = getid3_lib::LittleEndian2Int(substr($asf_header_extension_object_data, $offset, 1)); $offset += 1; break; default: $unhandled_sections++; if ($this->GUIDname($thisObject['guid_text'])) { $this->warning('unhandled Header Extension Object GUID "'.$this->GUIDname($thisObject['guid_text']).'" {'.$thisObject['guid_text'].'} at offset '.($offset - 16 - 8)); } else { $this->warning('unknown Header Extension Object GUID {'.$thisObject['guid_text'].'} in at offset '.($offset - 16 - 8)); } break; } $HeaderExtensionObjectParsed[] = $thisObject; $objectOffset += $thisObject['size']; } return $HeaderExtensionObjectParsed; } /** * @param int $id * * @return string */ public static function metadataLibraryObjectDataTypeLookup($id) { static $lookup = array( 0x0000 => 'Unicode string', // The data consists of a sequence of Unicode characters 0x0001 => 'BYTE array', // The type of the data is implementation-specific 0x0002 => 'BOOL', // The data is 2 bytes long and should be interpreted as a 16-bit unsigned integer. Only 0x0000 or 0x0001 are permitted values 0x0003 => 'DWORD', // The data is 4 bytes long and should be interpreted as a 32-bit unsigned integer 0x0004 => 'QWORD', // The data is 8 bytes long and should be interpreted as a 64-bit unsigned integer 0x0005 => 'WORD', // The data is 2 bytes long and should be interpreted as a 16-bit unsigned integer 0x0006 => 'GUID', // The data is 16 bytes long and should be interpreted as a 128-bit GUID ); return (isset($lookup[$id]) ? $lookup[$id] : 'invalid'); } /** * @param string $data * * @return array */ public function ASF_WMpicture(&$data) { //typedef struct _WMPicture{ // LPWSTR pwszMIMEType; // BYTE bPictureType; // LPWSTR pwszDescription; // DWORD dwDataLen; // BYTE* pbData; //} WM_PICTURE; $WMpicture = array(); $offset = 0; $WMpicture['image_type_id'] = getid3_lib::LittleEndian2Int(substr($data, $offset, 1)); $offset += 1; $WMpicture['image_type'] = self::WMpictureTypeLookup($WMpicture['image_type_id']); $WMpicture['image_size'] = getid3_lib::LittleEndian2Int(substr($data, $offset, 4)); $offset += 4; $WMpicture['image_mime'] = ''; do { $next_byte_pair = substr($data, $offset, 2); $offset += 2; $WMpicture['image_mime'] .= $next_byte_pair; } while ($next_byte_pair !== "\x00\x00"); $WMpicture['image_description'] = ''; do { $next_byte_pair = substr($data, $offset, 2); $offset += 2; $WMpicture['image_description'] .= $next_byte_pair; } while ($next_byte_pair !== "\x00\x00"); $WMpicture['dataoffset'] = $offset; $WMpicture['data'] = substr($data, $offset); $imageinfo = array(); $WMpicture['image_mime'] = ''; $imagechunkcheck = getid3_lib::GetDataImageSize($WMpicture['data'], $imageinfo); unset($imageinfo); if (!empty($imagechunkcheck)) { $WMpicture['image_mime'] = image_type_to_mime_type($imagechunkcheck[2]); } if (!isset($this->getid3->info['asf']['comments']['picture'])) { $this->getid3->info['asf']['comments']['picture'] = array(); } $this->getid3->info['asf']['comments']['picture'][] = array('data'=>$WMpicture['data'], 'image_mime'=>$WMpicture['image_mime']); return $WMpicture; } /** * Remove terminator 00 00 and convert UTF-16LE to Latin-1. * * @param string $string * * @return string */ public static function TrimConvert($string) { return trim(getid3_lib::iconv_fallback('UTF-16LE', 'ISO-8859-1', self::TrimTerm($string)), ' '); } /** * Remove terminator 00 00. * * @param string $string * * @return string */ public static function TrimTerm($string) { // remove terminator, only if present (it should be, but...) if (substr($string, -2) === "\x00\x00") { $string = substr($string, 0, -2); } return $string; } } module.tag.id3v2.php 0000644 00000456165 15054343026 0010265 0 ustar 00 <?php ///////////////////////////////////////////////////////////////// /// 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.tag.id3v2.php // // module for analyzing ID3v2 tags // // dependencies: module.tag.id3v1.php // // /// ///////////////////////////////////////////////////////////////// if (!defined('GETID3_INCLUDEPATH')) { // prevent path-exposing attacks that access modules directly on public webservers exit; } getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.tag.id3v1.php', __FILE__, true); class getid3_id3v2 extends getid3_handler { public $StartingOffset = 0; /** * @return bool */ public function Analyze() { $info = &$this->getid3->info; // Overall tag structure: // +-----------------------------+ // | Header (10 bytes) | // +-----------------------------+ // | Extended Header | // | (variable length, OPTIONAL) | // +-----------------------------+ // | Frames (variable length) | // +-----------------------------+ // | Padding | // | (variable length, OPTIONAL) | // +-----------------------------+ // | Footer (10 bytes, OPTIONAL) | // +-----------------------------+ // Header // ID3v2/file identifier "ID3" // ID3v2 version $04 00 // ID3v2 flags (%ab000000 in v2.2, %abc00000 in v2.3, %abcd0000 in v2.4.x) // ID3v2 size 4 * %0xxxxxxx // shortcuts $info['id3v2']['header'] = true; $thisfile_id3v2 = &$info['id3v2']; $thisfile_id3v2['flags'] = array(); $thisfile_id3v2_flags = &$thisfile_id3v2['flags']; $this->fseek($this->StartingOffset); $header = $this->fread(10); if (substr($header, 0, 3) == 'ID3' && strlen($header) == 10) { $thisfile_id3v2['majorversion'] = ord($header[3]); $thisfile_id3v2['minorversion'] = ord($header[4]); // shortcut $id3v2_majorversion = &$thisfile_id3v2['majorversion']; } else { unset($info['id3v2']); return false; } if ($id3v2_majorversion > 4) { // this script probably won't correctly parse ID3v2.5.x and above (if it ever exists) $this->error('this script only parses up to ID3v2.4.x - this tag is ID3v2.'.$id3v2_majorversion.'.'.$thisfile_id3v2['minorversion']); return false; } $id3_flags = ord($header[5]); switch ($id3v2_majorversion) { case 2: // %ab000000 in v2.2 $thisfile_id3v2_flags['unsynch'] = (bool) ($id3_flags & 0x80); // a - Unsynchronisation $thisfile_id3v2_flags['compression'] = (bool) ($id3_flags & 0x40); // b - Compression break; case 3: // %abc00000 in v2.3 $thisfile_id3v2_flags['unsynch'] = (bool) ($id3_flags & 0x80); // a - Unsynchronisation $thisfile_id3v2_flags['exthead'] = (bool) ($id3_flags & 0x40); // b - Extended header $thisfile_id3v2_flags['experim'] = (bool) ($id3_flags & 0x20); // c - Experimental indicator break; case 4: // %abcd0000 in v2.4 $thisfile_id3v2_flags['unsynch'] = (bool) ($id3_flags & 0x80); // a - Unsynchronisation $thisfile_id3v2_flags['exthead'] = (bool) ($id3_flags & 0x40); // b - Extended header $thisfile_id3v2_flags['experim'] = (bool) ($id3_flags & 0x20); // c - Experimental indicator $thisfile_id3v2_flags['isfooter'] = (bool) ($id3_flags & 0x10); // d - Footer present break; } $thisfile_id3v2['headerlength'] = getid3_lib::BigEndian2Int(substr($header, 6, 4), 1) + 10; // length of ID3v2 tag in 10-byte header doesn't include 10-byte header length $thisfile_id3v2['tag_offset_start'] = $this->StartingOffset; $thisfile_id3v2['tag_offset_end'] = $thisfile_id3v2['tag_offset_start'] + $thisfile_id3v2['headerlength']; // create 'encoding' key - used by getid3::HandleAllTags() // in ID3v2 every field can have it's own encoding type // so force everything to UTF-8 so it can be handled consistantly $thisfile_id3v2['encoding'] = 'UTF-8'; // Frames // All ID3v2 frames consists of one frame header followed by one or more // fields containing the actual information. The header is always 10 // bytes and laid out as follows: // // Frame ID $xx xx xx xx (four characters) // Size 4 * %0xxxxxxx // Flags $xx xx $sizeofframes = $thisfile_id3v2['headerlength'] - 10; // not including 10-byte initial header if (!empty($thisfile_id3v2['exthead']['length'])) { $sizeofframes -= ($thisfile_id3v2['exthead']['length'] + 4); } if (!empty($thisfile_id3v2_flags['isfooter'])) { $sizeofframes -= 10; // footer takes last 10 bytes of ID3v2 header, after frame data, before audio } if ($sizeofframes > 0) { $framedata = $this->fread($sizeofframes); // read all frames from file into $framedata variable // if entire frame data is unsynched, de-unsynch it now (ID3v2.3.x) if (!empty($thisfile_id3v2_flags['unsynch']) && ($id3v2_majorversion <= 3)) { $framedata = $this->DeUnsynchronise($framedata); } // [in ID3v2.4.0] Unsynchronisation [S:6.1] is done on frame level, instead // of on tag level, making it easier to skip frames, increasing the streamability // of the tag. The unsynchronisation flag in the header [S:3.1] indicates that // there exists an unsynchronised frame, while the new unsynchronisation flag in // the frame header [S:4.1.2] indicates unsynchronisation. //$framedataoffset = 10 + ($thisfile_id3v2['exthead']['length'] ? $thisfile_id3v2['exthead']['length'] + 4 : 0); // how many bytes into the stream - start from after the 10-byte header (and extended header length+4, if present) $framedataoffset = 10; // how many bytes into the stream - start from after the 10-byte header // Extended Header if (!empty($thisfile_id3v2_flags['exthead'])) { $extended_header_offset = 0; if ($id3v2_majorversion == 3) { // v2.3 definition: //Extended header size $xx xx xx xx // 32-bit integer //Extended Flags $xx xx // %x0000000 %00000000 // v2.3 // x - CRC data present //Size of padding $xx xx xx xx $thisfile_id3v2['exthead']['length'] = getid3_lib::BigEndian2Int(substr($framedata, $extended_header_offset, 4), 0); $extended_header_offset += 4; $thisfile_id3v2['exthead']['flag_bytes'] = 2; $thisfile_id3v2['exthead']['flag_raw'] = getid3_lib::BigEndian2Int(substr($framedata, $extended_header_offset, $thisfile_id3v2['exthead']['flag_bytes'])); $extended_header_offset += $thisfile_id3v2['exthead']['flag_bytes']; $thisfile_id3v2['exthead']['flags']['crc'] = (bool) ($thisfile_id3v2['exthead']['flag_raw'] & 0x8000); $thisfile_id3v2['exthead']['padding_size'] = getid3_lib::BigEndian2Int(substr($framedata, $extended_header_offset, 4)); $extended_header_offset += 4; if ($thisfile_id3v2['exthead']['flags']['crc']) { $thisfile_id3v2['exthead']['flag_data']['crc'] = getid3_lib::BigEndian2Int(substr($framedata, $extended_header_offset, 4)); $extended_header_offset += 4; } $extended_header_offset += $thisfile_id3v2['exthead']['padding_size']; } elseif ($id3v2_majorversion == 4) { // v2.4 definition: //Extended header size 4 * %0xxxxxxx // 28-bit synchsafe integer //Number of flag bytes $01 //Extended Flags $xx // %0bcd0000 // v2.4 // b - Tag is an update // Flag data length $00 // c - CRC data present // Flag data length $05 // Total frame CRC 5 * %0xxxxxxx // d - Tag restrictions // Flag data length $01 $thisfile_id3v2['exthead']['length'] = getid3_lib::BigEndian2Int(substr($framedata, $extended_header_offset, 4), true); $extended_header_offset += 4; $thisfile_id3v2['exthead']['flag_bytes'] = getid3_lib::BigEndian2Int(substr($framedata, $extended_header_offset, 1)); // should always be 1 $extended_header_offset += 1; $thisfile_id3v2['exthead']['flag_raw'] = getid3_lib::BigEndian2Int(substr($framedata, $extended_header_offset, $thisfile_id3v2['exthead']['flag_bytes'])); $extended_header_offset += $thisfile_id3v2['exthead']['flag_bytes']; $thisfile_id3v2['exthead']['flags']['update'] = (bool) ($thisfile_id3v2['exthead']['flag_raw'] & 0x40); $thisfile_id3v2['exthead']['flags']['crc'] = (bool) ($thisfile_id3v2['exthead']['flag_raw'] & 0x20); $thisfile_id3v2['exthead']['flags']['restrictions'] = (bool) ($thisfile_id3v2['exthead']['flag_raw'] & 0x10); if ($thisfile_id3v2['exthead']['flags']['update']) { $ext_header_chunk_length = getid3_lib::BigEndian2Int(substr($framedata, $extended_header_offset, 1)); // should be 0 $extended_header_offset += 1; } if ($thisfile_id3v2['exthead']['flags']['crc']) { $ext_header_chunk_length = getid3_lib::BigEndian2Int(substr($framedata, $extended_header_offset, 1)); // should be 5 $extended_header_offset += 1; $thisfile_id3v2['exthead']['flag_data']['crc'] = getid3_lib::BigEndian2Int(substr($framedata, $extended_header_offset, $ext_header_chunk_length), true, false); $extended_header_offset += $ext_header_chunk_length; } if ($thisfile_id3v2['exthead']['flags']['restrictions']) { $ext_header_chunk_length = getid3_lib::BigEndian2Int(substr($framedata, $extended_header_offset, 1)); // should be 1 $extended_header_offset += 1; // %ppqrrstt $restrictions_raw = getid3_lib::BigEndian2Int(substr($framedata, $extended_header_offset, 1)); $extended_header_offset += 1; $thisfile_id3v2['exthead']['flags']['restrictions']['tagsize'] = ($restrictions_raw & 0xC0) >> 6; // p - Tag size restrictions $thisfile_id3v2['exthead']['flags']['restrictions']['textenc'] = ($restrictions_raw & 0x20) >> 5; // q - Text encoding restrictions $thisfile_id3v2['exthead']['flags']['restrictions']['textsize'] = ($restrictions_raw & 0x18) >> 3; // r - Text fields size restrictions $thisfile_id3v2['exthead']['flags']['restrictions']['imgenc'] = ($restrictions_raw & 0x04) >> 2; // s - Image encoding restrictions $thisfile_id3v2['exthead']['flags']['restrictions']['imgsize'] = ($restrictions_raw & 0x03) >> 0; // t - Image size restrictions $thisfile_id3v2['exthead']['flags']['restrictions_text']['tagsize'] = $this->LookupExtendedHeaderRestrictionsTagSizeLimits($thisfile_id3v2['exthead']['flags']['restrictions']['tagsize']); $thisfile_id3v2['exthead']['flags']['restrictions_text']['textenc'] = $this->LookupExtendedHeaderRestrictionsTextEncodings($thisfile_id3v2['exthead']['flags']['restrictions']['textenc']); $thisfile_id3v2['exthead']['flags']['restrictions_text']['textsize'] = $this->LookupExtendedHeaderRestrictionsTextFieldSize($thisfile_id3v2['exthead']['flags']['restrictions']['textsize']); $thisfile_id3v2['exthead']['flags']['restrictions_text']['imgenc'] = $this->LookupExtendedHeaderRestrictionsImageEncoding($thisfile_id3v2['exthead']['flags']['restrictions']['imgenc']); $thisfile_id3v2['exthead']['flags']['restrictions_text']['imgsize'] = $this->LookupExtendedHeaderRestrictionsImageSizeSize($thisfile_id3v2['exthead']['flags']['restrictions']['imgsize']); } if ($thisfile_id3v2['exthead']['length'] != $extended_header_offset) { $this->warning('ID3v2.4 extended header length mismatch (expecting '.intval($thisfile_id3v2['exthead']['length']).', found '.intval($extended_header_offset).')'); } } $framedataoffset += $extended_header_offset; $framedata = substr($framedata, $extended_header_offset); } // end extended header while (isset($framedata) && (strlen($framedata) > 0)) { // cycle through until no more frame data is left to parse if (strlen($framedata) <= $this->ID3v2HeaderLength($id3v2_majorversion)) { // insufficient room left in ID3v2 header for actual data - must be padding $thisfile_id3v2['padding']['start'] = $framedataoffset; $thisfile_id3v2['padding']['length'] = strlen($framedata); $thisfile_id3v2['padding']['valid'] = true; for ($i = 0; $i < $thisfile_id3v2['padding']['length']; $i++) { if ($framedata[$i] != "\x00") { $thisfile_id3v2['padding']['valid'] = false; $thisfile_id3v2['padding']['errorpos'] = $thisfile_id3v2['padding']['start'] + $i; $this->warning('Invalid ID3v2 padding found at offset '.$thisfile_id3v2['padding']['errorpos'].' (the remaining '.($thisfile_id3v2['padding']['length'] - $i).' bytes are considered invalid)'); break; } } break; // skip rest of ID3v2 header } $frame_header = null; $frame_name = null; $frame_size = null; $frame_flags = null; if ($id3v2_majorversion == 2) { // Frame ID $xx xx xx (three characters) // Size $xx xx xx (24-bit integer) // Flags $xx xx $frame_header = substr($framedata, 0, 6); // take next 6 bytes for header $framedata = substr($framedata, 6); // and leave the rest in $framedata $frame_name = substr($frame_header, 0, 3); $frame_size = getid3_lib::BigEndian2Int(substr($frame_header, 3, 3), 0); $frame_flags = 0; // not used for anything in ID3v2.2, just set to avoid E_NOTICEs } elseif ($id3v2_majorversion > 2) { // Frame ID $xx xx xx xx (four characters) // Size $xx xx xx xx (32-bit integer in v2.3, 28-bit synchsafe in v2.4+) // Flags $xx xx $frame_header = substr($framedata, 0, 10); // take next 10 bytes for header $framedata = substr($framedata, 10); // and leave the rest in $framedata $frame_name = substr($frame_header, 0, 4); if ($id3v2_majorversion == 3) { $frame_size = getid3_lib::BigEndian2Int(substr($frame_header, 4, 4), 0); // 32-bit integer } else { // ID3v2.4+ $frame_size = getid3_lib::BigEndian2Int(substr($frame_header, 4, 4), 1); // 32-bit synchsafe integer (28-bit value) } if ($frame_size < (strlen($framedata) + 4)) { $nextFrameID = substr($framedata, $frame_size, 4); if ($this->IsValidID3v2FrameName($nextFrameID, $id3v2_majorversion)) { // next frame is OK } elseif (($frame_name == "\x00".'MP3') || ($frame_name == "\x00\x00".'MP') || ($frame_name == ' MP3') || ($frame_name == 'MP3e')) { // MP3ext known broken frames - "ok" for the purposes of this test } elseif (($id3v2_majorversion == 4) && ($this->IsValidID3v2FrameName(substr($framedata, getid3_lib::BigEndian2Int(substr($frame_header, 4, 4), 0), 4), 3))) { $this->warning('ID3v2 tag written as ID3v2.4, but with non-synchsafe integers (ID3v2.3 style). Older versions of (Helium2; iTunes) are known culprits of this. Tag has been parsed as ID3v2.3'); $id3v2_majorversion = 3; $frame_size = getid3_lib::BigEndian2Int(substr($frame_header, 4, 4), 0); // 32-bit integer } } $frame_flags = getid3_lib::BigEndian2Int(substr($frame_header, 8, 2)); } if ((($id3v2_majorversion == 2) && ($frame_name == "\x00\x00\x00")) || ($frame_name == "\x00\x00\x00\x00")) { // padding encountered $thisfile_id3v2['padding']['start'] = $framedataoffset; $thisfile_id3v2['padding']['length'] = strlen($frame_header) + strlen($framedata); $thisfile_id3v2['padding']['valid'] = true; $len = strlen($framedata); for ($i = 0; $i < $len; $i++) { if ($framedata[$i] != "\x00") { $thisfile_id3v2['padding']['valid'] = false; $thisfile_id3v2['padding']['errorpos'] = $thisfile_id3v2['padding']['start'] + $i; $this->warning('Invalid ID3v2 padding found at offset '.$thisfile_id3v2['padding']['errorpos'].' (the remaining '.($thisfile_id3v2['padding']['length'] - $i).' bytes are considered invalid)'); break; } } break; // skip rest of ID3v2 header } if ($iTunesBrokenFrameNameFixed = self::ID3v22iTunesBrokenFrameName($frame_name)) { $this->warning('error parsing "'.$frame_name.'" ('.$framedataoffset.' bytes into the ID3v2.'.$id3v2_majorversion.' tag). (ERROR: IsValidID3v2FrameName("'.str_replace("\x00", ' ', $frame_name).'", '.$id3v2_majorversion.'))). [Note: this particular error has been known to happen with tags edited by iTunes (versions "X v2.0.3", "v3.0.1", "v7.0.0.70" are known-guilty, probably others too)]. Translated frame name from "'.str_replace("\x00", ' ', $frame_name).'" to "'.$iTunesBrokenFrameNameFixed.'" for parsing.'); $frame_name = $iTunesBrokenFrameNameFixed; } if (($frame_size <= strlen($framedata)) && ($this->IsValidID3v2FrameName($frame_name, $id3v2_majorversion))) { $parsedFrame = array(); $parsedFrame['frame_name'] = $frame_name; $parsedFrame['frame_flags_raw'] = $frame_flags; $parsedFrame['data'] = substr($framedata, 0, $frame_size); $parsedFrame['datalength'] = getid3_lib::CastAsInt($frame_size); $parsedFrame['dataoffset'] = $framedataoffset; $this->ParseID3v2Frame($parsedFrame); $thisfile_id3v2[$frame_name][] = $parsedFrame; $framedata = substr($framedata, $frame_size); } else { // invalid frame length or FrameID if ($frame_size <= strlen($framedata)) { if ($this->IsValidID3v2FrameName(substr($framedata, $frame_size, 4), $id3v2_majorversion)) { // next frame is valid, just skip the current frame $framedata = substr($framedata, $frame_size); $this->warning('Next ID3v2 frame is valid, skipping current frame.'); } else { // next frame is invalid too, abort processing //unset($framedata); $framedata = null; $this->error('Next ID3v2 frame is also invalid, aborting processing.'); } } elseif ($frame_size == strlen($framedata)) { // this is the last frame, just skip $this->warning('This was the last ID3v2 frame.'); } else { // next frame is invalid too, abort processing //unset($framedata); $framedata = null; $this->warning('Invalid ID3v2 frame size, aborting.'); } if (!$this->IsValidID3v2FrameName($frame_name, $id3v2_majorversion)) { switch ($frame_name) { case "\x00\x00".'MP': case "\x00".'MP3': case ' MP3': case 'MP3e': case "\x00".'MP': case ' MP': case 'MP3': $this->warning('error parsing "'.$frame_name.'" ('.$framedataoffset.' bytes into the ID3v2.'.$id3v2_majorversion.' tag). (ERROR: !IsValidID3v2FrameName("'.str_replace("\x00", ' ', $frame_name).'", '.$id3v2_majorversion.'))). [Note: this particular error has been known to happen with tags edited by "MP3ext (www.mutschler.de/mp3ext/)"]'); break; default: $this->warning('error parsing "'.$frame_name.'" ('.$framedataoffset.' bytes into the ID3v2.'.$id3v2_majorversion.' tag). (ERROR: !IsValidID3v2FrameName("'.str_replace("\x00", ' ', $frame_name).'", '.$id3v2_majorversion.'))).'); break; } } elseif (!isset($framedata) || ($frame_size > strlen($framedata))) { $this->error('error parsing "'.$frame_name.'" ('.$framedataoffset.' bytes into the ID3v2.'.$id3v2_majorversion.' tag). (ERROR: $frame_size ('.$frame_size.') > strlen($framedata) ('.(isset($framedata) ? strlen($framedata) : 'null').')).'); } else { $this->error('error parsing "'.$frame_name.'" ('.$framedataoffset.' bytes into the ID3v2.'.$id3v2_majorversion.' tag).'); } } $framedataoffset += ($frame_size + $this->ID3v2HeaderLength($id3v2_majorversion)); } } // Footer // The footer is a copy of the header, but with a different identifier. // ID3v2 identifier "3DI" // ID3v2 version $04 00 // ID3v2 flags %abcd0000 // ID3v2 size 4 * %0xxxxxxx if (isset($thisfile_id3v2_flags['isfooter']) && $thisfile_id3v2_flags['isfooter']) { $footer = $this->fread(10); if (substr($footer, 0, 3) == '3DI') { $thisfile_id3v2['footer'] = true; $thisfile_id3v2['majorversion_footer'] = ord($footer[3]); $thisfile_id3v2['minorversion_footer'] = ord($footer[4]); } if ($thisfile_id3v2['majorversion_footer'] <= 4) { $id3_flags = ord($footer[5]); $thisfile_id3v2_flags['unsynch_footer'] = (bool) ($id3_flags & 0x80); $thisfile_id3v2_flags['extfoot_footer'] = (bool) ($id3_flags & 0x40); $thisfile_id3v2_flags['experim_footer'] = (bool) ($id3_flags & 0x20); $thisfile_id3v2_flags['isfooter_footer'] = (bool) ($id3_flags & 0x10); $thisfile_id3v2['footerlength'] = getid3_lib::BigEndian2Int(substr($footer, 6, 4), 1); } } // end footer if (isset($thisfile_id3v2['comments']['genre'])) { $genres = array(); foreach ($thisfile_id3v2['comments']['genre'] as $key => $value) { foreach ($this->ParseID3v2GenreString($value) as $genre) { $genres[] = $genre; } } $thisfile_id3v2['comments']['genre'] = array_unique($genres); unset($key, $value, $genres, $genre); } if (isset($thisfile_id3v2['comments']['track_number'])) { foreach ($thisfile_id3v2['comments']['track_number'] as $key => $value) { if (strstr($value, '/')) { list($thisfile_id3v2['comments']['track_number'][$key], $thisfile_id3v2['comments']['totaltracks'][$key]) = explode('/', $thisfile_id3v2['comments']['track_number'][$key]); } } } if (!isset($thisfile_id3v2['comments']['year']) && !empty($thisfile_id3v2['comments']['recording_time'][0]) && preg_match('#^([0-9]{4})#', trim($thisfile_id3v2['comments']['recording_time'][0]), $matches)) { $thisfile_id3v2['comments']['year'] = array($matches[1]); } if (!empty($thisfile_id3v2['TXXX'])) { // MediaMonkey does this, maybe others: write a blank RGAD frame, but put replay-gain adjustment values in TXXX frames foreach ($thisfile_id3v2['TXXX'] as $txxx_array) { switch ($txxx_array['description']) { case 'replaygain_track_gain': if (empty($info['replay_gain']['track']['adjustment']) && !empty($txxx_array['data'])) { $info['replay_gain']['track']['adjustment'] = floatval(trim(str_replace('dB', '', $txxx_array['data']))); } break; case 'replaygain_track_peak': if (empty($info['replay_gain']['track']['peak']) && !empty($txxx_array['data'])) { $info['replay_gain']['track']['peak'] = floatval($txxx_array['data']); } break; case 'replaygain_album_gain': if (empty($info['replay_gain']['album']['adjustment']) && !empty($txxx_array['data'])) { $info['replay_gain']['album']['adjustment'] = floatval(trim(str_replace('dB', '', $txxx_array['data']))); } break; } } } // Set avdataoffset $info['avdataoffset'] = $thisfile_id3v2['headerlength']; if (isset($thisfile_id3v2['footer'])) { $info['avdataoffset'] += 10; } return true; } /** * @param string $genrestring * * @return array */ public function ParseID3v2GenreString($genrestring) { // Parse genres into arrays of genreName and genreID // ID3v2.2.x, ID3v2.3.x: '(21)' or '(4)Eurodisco' or '(51)(39)' or '(55)((I think...)' // ID3v2.4.x: '21' $00 'Eurodisco' $00 $clean_genres = array(); // hack-fixes for some badly-written ID3v2.3 taggers, while trying not to break correctly-written tags if (($this->getid3->info['id3v2']['majorversion'] == 3) && !preg_match('#[\x00]#', $genrestring)) { // note: MusicBrainz Picard incorrectly stores plaintext genres separated by "/" when writing in ID3v2.3 mode, hack-fix here: // replace / with NULL, then replace back the two ID3v1 genres that legitimately have "/" as part of the single genre name if (strpos($genrestring, '/') !== false) { $LegitimateSlashedGenreList = array( // https://github.com/JamesHeinrich/getID3/issues/223 'Pop/Funk', // ID3v1 genre #62 - https://en.wikipedia.org/wiki/ID3#standard 'Cut-up/DJ', // Discogs - https://www.discogs.com/style/cut-up/dj 'RnB/Swing', // Discogs - https://www.discogs.com/style/rnb/swing 'Funk / Soul', // Discogs (note spaces) - https://www.discogs.com/genre/funk+%2F+soul ); $genrestring = str_replace('/', "\x00", $genrestring); foreach ($LegitimateSlashedGenreList as $SlashedGenre) { $genrestring = str_ireplace(str_replace('/', "\x00", $SlashedGenre), $SlashedGenre, $genrestring); } } // some other taggers separate multiple genres with semicolon, e.g. "Heavy Metal;Thrash Metal;Metal" if (strpos($genrestring, ';') !== false) { $genrestring = str_replace(';', "\x00", $genrestring); } } if (strpos($genrestring, "\x00") === false) { $genrestring = preg_replace('#\(([0-9]{1,3})\)#', '$1'."\x00", $genrestring); } $genre_elements = explode("\x00", $genrestring); foreach ($genre_elements as $element) { $element = trim($element); if ($element) { if (preg_match('#^[0-9]{1,3}$#', $element)) { $clean_genres[] = getid3_id3v1::LookupGenreName($element); } else { $clean_genres[] = str_replace('((', '(', $element); } } } return $clean_genres; } /** * @param array $parsedFrame * * @return bool */ public function ParseID3v2Frame(&$parsedFrame) { // shortcuts $info = &$this->getid3->info; $id3v2_majorversion = $info['id3v2']['majorversion']; $parsedFrame['framenamelong'] = $this->FrameNameLongLookup($parsedFrame['frame_name']); if (empty($parsedFrame['framenamelong'])) { unset($parsedFrame['framenamelong']); } $parsedFrame['framenameshort'] = $this->FrameNameShortLookup($parsedFrame['frame_name']); if (empty($parsedFrame['framenameshort'])) { unset($parsedFrame['framenameshort']); } if ($id3v2_majorversion >= 3) { // frame flags are not part of the ID3v2.2 standard if ($id3v2_majorversion == 3) { // Frame Header Flags // %abc00000 %ijk00000 $parsedFrame['flags']['TagAlterPreservation'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x8000); // a - Tag alter preservation $parsedFrame['flags']['FileAlterPreservation'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x4000); // b - File alter preservation $parsedFrame['flags']['ReadOnly'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x2000); // c - Read only $parsedFrame['flags']['compression'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x0080); // i - Compression $parsedFrame['flags']['Encryption'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x0040); // j - Encryption $parsedFrame['flags']['GroupingIdentity'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x0020); // k - Grouping identity } elseif ($id3v2_majorversion == 4) { // Frame Header Flags // %0abc0000 %0h00kmnp $parsedFrame['flags']['TagAlterPreservation'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x4000); // a - Tag alter preservation $parsedFrame['flags']['FileAlterPreservation'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x2000); // b - File alter preservation $parsedFrame['flags']['ReadOnly'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x1000); // c - Read only $parsedFrame['flags']['GroupingIdentity'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x0040); // h - Grouping identity $parsedFrame['flags']['compression'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x0008); // k - Compression $parsedFrame['flags']['Encryption'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x0004); // m - Encryption $parsedFrame['flags']['Unsynchronisation'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x0002); // n - Unsynchronisation $parsedFrame['flags']['DataLengthIndicator'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x0001); // p - Data length indicator // Frame-level de-unsynchronisation - ID3v2.4 if ($parsedFrame['flags']['Unsynchronisation']) { $parsedFrame['data'] = $this->DeUnsynchronise($parsedFrame['data']); } if ($parsedFrame['flags']['DataLengthIndicator']) { $parsedFrame['data_length_indicator'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], 0, 4), 1); $parsedFrame['data'] = substr($parsedFrame['data'], 4); } } // Frame-level de-compression if ($parsedFrame['flags']['compression']) { $parsedFrame['decompressed_size'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], 0, 4)); if (!function_exists('gzuncompress')) { $this->warning('gzuncompress() support required to decompress ID3v2 frame "'.$parsedFrame['frame_name'].'"'); } else { if ($decompresseddata = @gzuncompress(substr($parsedFrame['data'], 4))) { //if ($decompresseddata = @gzuncompress($parsedFrame['data'])) { $parsedFrame['data'] = $decompresseddata; unset($decompresseddata); } else { $this->warning('gzuncompress() failed on compressed contents of ID3v2 frame "'.$parsedFrame['frame_name'].'"'); } } } } if (!empty($parsedFrame['flags']['DataLengthIndicator'])) { if ($parsedFrame['data_length_indicator'] != strlen($parsedFrame['data'])) { $this->warning('ID3v2 frame "'.$parsedFrame['frame_name'].'" should be '.$parsedFrame['data_length_indicator'].' bytes long according to DataLengthIndicator, but found '.strlen($parsedFrame['data']).' bytes of data'); } } if (isset($parsedFrame['datalength']) && ($parsedFrame['datalength'] == 0)) { $warning = 'Frame "'.$parsedFrame['frame_name'].'" at offset '.$parsedFrame['dataoffset'].' has no data portion'; switch ($parsedFrame['frame_name']) { case 'WCOM': $warning .= ' (this is known to happen with files tagged by RioPort)'; break; default: break; } $this->warning($warning); } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'UFID')) || // 4.1 UFID Unique file identifier (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'UFI'))) { // 4.1 UFI Unique file identifier // There may be more than one 'UFID' frame in a tag, // but only one with the same 'Owner identifier'. // <Header for 'Unique file identifier', ID: 'UFID'> // Owner identifier <text string> $00 // Identifier <up to 64 bytes binary data> $exploded = explode("\x00", $parsedFrame['data'], 2); $parsedFrame['ownerid'] = (isset($exploded[0]) ? $exploded[0] : ''); $parsedFrame['data'] = (isset($exploded[1]) ? $exploded[1] : ''); } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'TXXX')) || // 4.2.2 TXXX User defined text information frame (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'TXX'))) { // 4.2.2 TXX User defined text information frame // There may be more than one 'TXXX' frame in each tag, // but only one with the same description. // <Header for 'User defined text information frame', ID: 'TXXX'> // Text encoding $xx // Description <text string according to encoding> $00 (00) // Value <text string according to encoding> $frame_offset = 0; $frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $frame_textencoding_terminator = $this->TextEncodingTerminatorLookup($frame_textencoding); if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) { $this->warning('Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding'); $frame_textencoding_terminator = "\x00"; } $frame_terminatorpos = strpos($parsedFrame['data'], $frame_textencoding_terminator, $frame_offset); if (ord(substr($parsedFrame['data'], $frame_terminatorpos + strlen($frame_textencoding_terminator), 1)) === 0) { $frame_terminatorpos++; // strpos() fooled because 2nd byte of Unicode chars are often 0x00 } $parsedFrame['description'] = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); $parsedFrame['description'] = $this->MakeUTF16emptyStringEmpty($parsedFrame['description']); $parsedFrame['encodingid'] = $frame_textencoding; $parsedFrame['encoding'] = $this->TextEncodingNameLookup($frame_textencoding); $parsedFrame['description'] = trim(getid3_lib::iconv_fallback($parsedFrame['encoding'], $info['id3v2']['encoding'], $parsedFrame['description'])); $parsedFrame['data'] = substr($parsedFrame['data'], $frame_terminatorpos + strlen($frame_textencoding_terminator)); $parsedFrame['data'] = $this->RemoveStringTerminator($parsedFrame['data'], $frame_textencoding_terminator); if (!empty($parsedFrame['framenameshort']) && !empty($parsedFrame['data'])) { $commentkey = ($parsedFrame['description'] ? $parsedFrame['description'] : (isset($info['id3v2']['comments'][$parsedFrame['framenameshort']]) ? count($info['id3v2']['comments'][$parsedFrame['framenameshort']]) : 0)); if (!isset($info['id3v2']['comments'][$parsedFrame['framenameshort']]) || !array_key_exists($commentkey, $info['id3v2']['comments'][$parsedFrame['framenameshort']])) { $info['id3v2']['comments'][$parsedFrame['framenameshort']][$commentkey] = trim(getid3_lib::iconv_fallback($parsedFrame['encoding'], $info['id3v2']['encoding'], $parsedFrame['data'])); } else { $info['id3v2']['comments'][$parsedFrame['framenameshort']][] = trim(getid3_lib::iconv_fallback($parsedFrame['encoding'], $info['id3v2']['encoding'], $parsedFrame['data'])); } } //unset($parsedFrame['data']); do not unset, may be needed elsewhere, e.g. for replaygain } elseif ($parsedFrame['frame_name'][0] == 'T') { // 4.2. T??[?] Text information frame // There may only be one text information frame of its kind in an tag. // <Header for 'Text information frame', ID: 'T000' - 'TZZZ', // excluding 'TXXX' described in 4.2.6.> // Text encoding $xx // Information <text string(s) according to encoding> $frame_offset = 0; $frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1)); if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) { $this->warning('Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding'); } $parsedFrame['data'] = (string) substr($parsedFrame['data'], $frame_offset); $parsedFrame['data'] = $this->RemoveStringTerminator($parsedFrame['data'], $this->TextEncodingTerminatorLookup($frame_textencoding)); $parsedFrame['encodingid'] = $frame_textencoding; $parsedFrame['encoding'] = $this->TextEncodingNameLookup($frame_textencoding); if (!empty($parsedFrame['framenameshort']) && !empty($parsedFrame['data'])) { // ID3v2.3 specs say that TPE1 (and others) can contain multiple artist values separated with / // This of course breaks when an artist name contains slash character, e.g. "AC/DC" // MP3tag (maybe others) implement alternative system where multiple artists are null-separated, which makes more sense // getID3 will split null-separated artists into multiple artists and leave slash-separated ones to the user switch ($parsedFrame['encoding']) { case 'UTF-16': case 'UTF-16BE': case 'UTF-16LE': $wordsize = 2; break; case 'ISO-8859-1': case 'UTF-8': default: $wordsize = 1; break; } $Txxx_elements = array(); $Txxx_elements_start_offset = 0; for ($i = 0; $i < strlen($parsedFrame['data']); $i += $wordsize) { if (substr($parsedFrame['data'], $i, $wordsize) == str_repeat("\x00", $wordsize)) { $Txxx_elements[] = substr($parsedFrame['data'], $Txxx_elements_start_offset, $i - $Txxx_elements_start_offset); $Txxx_elements_start_offset = $i + $wordsize; } } $Txxx_elements[] = substr($parsedFrame['data'], $Txxx_elements_start_offset, $i - $Txxx_elements_start_offset); foreach ($Txxx_elements as $Txxx_element) { $string = getid3_lib::iconv_fallback($parsedFrame['encoding'], $info['id3v2']['encoding'], $Txxx_element); if (!empty($string)) { $info['id3v2']['comments'][$parsedFrame['framenameshort']][] = $string; } } unset($string, $wordsize, $i, $Txxx_elements, $Txxx_element, $Txxx_elements_start_offset); } } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'WXXX')) || // 4.3.2 WXXX User defined URL link frame (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'WXX'))) { // 4.3.2 WXX User defined URL link frame // There may be more than one 'WXXX' frame in each tag, // but only one with the same description // <Header for 'User defined URL link frame', ID: 'WXXX'> // Text encoding $xx // Description <text string according to encoding> $00 (00) // URL <text string> $frame_offset = 0; $frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $frame_textencoding_terminator = $this->TextEncodingTerminatorLookup($frame_textencoding); if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) { $this->warning('Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding'); $frame_textencoding_terminator = "\x00"; } $frame_terminatorpos = strpos($parsedFrame['data'], $frame_textencoding_terminator, $frame_offset); if (ord(substr($parsedFrame['data'], $frame_terminatorpos + strlen($frame_textencoding_terminator), 1)) === 0) { $frame_terminatorpos++; // strpos() fooled because 2nd byte of Unicode chars are often 0x00 } $parsedFrame['encodingid'] = $frame_textencoding; $parsedFrame['encoding'] = $this->TextEncodingNameLookup($frame_textencoding); $parsedFrame['description'] = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); // according to the frame text encoding $parsedFrame['url'] = substr($parsedFrame['data'], $frame_terminatorpos + strlen($frame_textencoding_terminator)); // always ISO-8859-1 $parsedFrame['description'] = $this->RemoveStringTerminator($parsedFrame['description'], $frame_textencoding_terminator); $parsedFrame['description'] = $this->MakeUTF16emptyStringEmpty($parsedFrame['description']); if (!empty($parsedFrame['framenameshort']) && $parsedFrame['url']) { $info['id3v2']['comments'][$parsedFrame['framenameshort']][] = getid3_lib::iconv_fallback('ISO-8859-1', $info['id3v2']['encoding'], $parsedFrame['url']); } unset($parsedFrame['data']); } elseif ($parsedFrame['frame_name'][0] == 'W') { // 4.3. W??? URL link frames // There may only be one URL link frame of its kind in a tag, // except when stated otherwise in the frame description // <Header for 'URL link frame', ID: 'W000' - 'WZZZ', excluding 'WXXX' // described in 4.3.2.> // URL <text string> $parsedFrame['url'] = trim($parsedFrame['data']); // always ISO-8859-1 if (!empty($parsedFrame['framenameshort']) && $parsedFrame['url']) { $info['id3v2']['comments'][$parsedFrame['framenameshort']][] = getid3_lib::iconv_fallback('ISO-8859-1', $info['id3v2']['encoding'], $parsedFrame['url']); } unset($parsedFrame['data']); } elseif ((($id3v2_majorversion == 3) && ($parsedFrame['frame_name'] == 'IPLS')) || // 4.4 IPLS Involved people list (ID3v2.3 only) (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'IPL'))) { // 4.4 IPL Involved people list (ID3v2.2 only) // http://id3.org/id3v2.3.0#sec4.4 // There may only be one 'IPL' frame in each tag // <Header for 'User defined URL link frame', ID: 'IPL'> // Text encoding $xx // People list strings <textstrings> $frame_offset = 0; $frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1)); if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) { $this->warning('Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding'); } $parsedFrame['encodingid'] = $frame_textencoding; $parsedFrame['encoding'] = $this->TextEncodingNameLookup($parsedFrame['encodingid']); $parsedFrame['data_raw'] = (string) substr($parsedFrame['data'], $frame_offset); // https://www.getid3.org/phpBB3/viewtopic.php?t=1369 // "this tag typically contains null terminated strings, which are associated in pairs" // "there are users that use the tag incorrectly" $IPLS_parts = array(); if (strpos($parsedFrame['data_raw'], "\x00") !== false) { $IPLS_parts_unsorted = array(); if (((strlen($parsedFrame['data_raw']) % 2) == 0) && ((substr($parsedFrame['data_raw'], 0, 2) == "\xFF\xFE") || (substr($parsedFrame['data_raw'], 0, 2) == "\xFE\xFF"))) { // UTF-16, be careful looking for null bytes since most 2-byte characters may contain one; you need to find twin null bytes, and on even padding $thisILPS = ''; for ($i = 0; $i < strlen($parsedFrame['data_raw']); $i += 2) { $twobytes = substr($parsedFrame['data_raw'], $i, 2); if ($twobytes === "\x00\x00") { $IPLS_parts_unsorted[] = getid3_lib::iconv_fallback($parsedFrame['encoding'], $info['id3v2']['encoding'], $thisILPS); $thisILPS = ''; } else { $thisILPS .= $twobytes; } } if (strlen($thisILPS) > 2) { // 2-byte BOM $IPLS_parts_unsorted[] = getid3_lib::iconv_fallback($parsedFrame['encoding'], $info['id3v2']['encoding'], $thisILPS); } } else { // ISO-8859-1 or UTF-8 or other single-byte-null character set $IPLS_parts_unsorted = explode("\x00", $parsedFrame['data_raw']); } if (count($IPLS_parts_unsorted) == 1) { // just a list of names, e.g. "Dino Baptiste, Jimmy Copley, John Gordon, Bernie Marsden, Sharon Watson" foreach ($IPLS_parts_unsorted as $key => $value) { $IPLS_parts_sorted = preg_split('#[;,\\r\\n\\t]#', $value); $position = ''; foreach ($IPLS_parts_sorted as $person) { $IPLS_parts[] = array('position'=>$position, 'person'=>$person); } } } elseif ((count($IPLS_parts_unsorted) % 2) == 0) { $position = ''; $person = ''; foreach ($IPLS_parts_unsorted as $key => $value) { if (($key % 2) == 0) { $position = $value; } else { $person = $value; $IPLS_parts[] = array('position'=>$position, 'person'=>$person); $position = ''; $person = ''; } } } else { foreach ($IPLS_parts_unsorted as $key => $value) { $IPLS_parts[] = array($value); } } } else { $IPLS_parts = preg_split('#[;,\\r\\n\\t]#', $parsedFrame['data_raw']); } $parsedFrame['data'] = $IPLS_parts; if (!empty($parsedFrame['framenameshort']) && !empty($parsedFrame['data'])) { $info['id3v2']['comments'][$parsedFrame['framenameshort']][] = $parsedFrame['data']; } } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'MCDI')) || // 4.4 MCDI Music CD identifier (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'MCI'))) { // 4.5 MCI Music CD identifier // There may only be one 'MCDI' frame in each tag // <Header for 'Music CD identifier', ID: 'MCDI'> // CD TOC <binary data> if (!empty($parsedFrame['framenameshort']) && !empty($parsedFrame['data'])) { $info['id3v2']['comments'][$parsedFrame['framenameshort']][] = $parsedFrame['data']; } } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'ETCO')) || // 4.5 ETCO Event timing codes (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'ETC'))) { // 4.6 ETC Event timing codes // There may only be one 'ETCO' frame in each tag // <Header for 'Event timing codes', ID: 'ETCO'> // Time stamp format $xx // Where time stamp format is: // $01 (32-bit value) MPEG frames from beginning of file // $02 (32-bit value) milliseconds from beginning of file // Followed by a list of key events in the following format: // Type of event $xx // Time stamp $xx (xx ...) // The 'Time stamp' is set to zero if directly at the beginning of the sound // or after the previous event. All events MUST be sorted in chronological order. $frame_offset = 0; $parsedFrame['timestampformat'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); while ($frame_offset < strlen($parsedFrame['data'])) { $parsedFrame['typeid'] = substr($parsedFrame['data'], $frame_offset++, 1); $parsedFrame['type'] = $this->ETCOEventLookup($parsedFrame['typeid']); $parsedFrame['timestamp'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 4)); $frame_offset += 4; } unset($parsedFrame['data']); } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'MLLT')) || // 4.6 MLLT MPEG location lookup table (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'MLL'))) { // 4.7 MLL MPEG location lookup table // There may only be one 'MLLT' frame in each tag // <Header for 'Location lookup table', ID: 'MLLT'> // MPEG frames between reference $xx xx // Bytes between reference $xx xx xx // Milliseconds between reference $xx xx xx // Bits for bytes deviation $xx // Bits for milliseconds dev. $xx // Then for every reference the following data is included; // Deviation in bytes %xxx.... // Deviation in milliseconds %xxx.... $frame_offset = 0; $parsedFrame['framesbetweenreferences'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], 0, 2)); $parsedFrame['bytesbetweenreferences'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], 2, 3)); $parsedFrame['msbetweenreferences'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], 5, 3)); $parsedFrame['bitsforbytesdeviation'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], 8, 1)); $parsedFrame['bitsformsdeviation'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], 9, 1)); $parsedFrame['data'] = substr($parsedFrame['data'], 10); $deviationbitstream = ''; while ($frame_offset < strlen($parsedFrame['data'])) { $deviationbitstream .= getid3_lib::BigEndian2Bin(substr($parsedFrame['data'], $frame_offset++, 1)); } $reference_counter = 0; while (strlen($deviationbitstream) > 0) { $parsedFrame[$reference_counter]['bytedeviation'] = bindec(substr($deviationbitstream, 0, $parsedFrame['bitsforbytesdeviation'])); $parsedFrame[$reference_counter]['msdeviation'] = bindec(substr($deviationbitstream, $parsedFrame['bitsforbytesdeviation'], $parsedFrame['bitsformsdeviation'])); $deviationbitstream = substr($deviationbitstream, $parsedFrame['bitsforbytesdeviation'] + $parsedFrame['bitsformsdeviation']); $reference_counter++; } unset($parsedFrame['data']); } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'SYTC')) || // 4.7 SYTC Synchronised tempo codes (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'STC'))) { // 4.8 STC Synchronised tempo codes // There may only be one 'SYTC' frame in each tag // <Header for 'Synchronised tempo codes', ID: 'SYTC'> // Time stamp format $xx // Tempo data <binary data> // Where time stamp format is: // $01 (32-bit value) MPEG frames from beginning of file // $02 (32-bit value) milliseconds from beginning of file $frame_offset = 0; $parsedFrame['timestampformat'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $timestamp_counter = 0; while ($frame_offset < strlen($parsedFrame['data'])) { $parsedFrame[$timestamp_counter]['tempo'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); if ($parsedFrame[$timestamp_counter]['tempo'] == 255) { $parsedFrame[$timestamp_counter]['tempo'] += ord(substr($parsedFrame['data'], $frame_offset++, 1)); } $parsedFrame[$timestamp_counter]['timestamp'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 4)); $frame_offset += 4; $timestamp_counter++; } unset($parsedFrame['data']); } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'USLT')) || // 4.8 USLT Unsynchronised lyric/text transcription (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'ULT'))) { // 4.9 ULT Unsynchronised lyric/text transcription // There may be more than one 'Unsynchronised lyrics/text transcription' frame // in each tag, but only one with the same language and content descriptor. // <Header for 'Unsynchronised lyrics/text transcription', ID: 'USLT'> // Text encoding $xx // Language $xx xx xx // Content descriptor <text string according to encoding> $00 (00) // Lyrics/text <full text string according to encoding> $frame_offset = 0; $frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $frame_textencoding_terminator = $this->TextEncodingTerminatorLookup($frame_textencoding); if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) { $this->warning('Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding'); $frame_textencoding_terminator = "\x00"; } if (strlen($parsedFrame['data']) >= (4 + strlen($frame_textencoding_terminator))) { // shouldn't be an issue but badly-written files have been spotted in the wild with not only no contents but also missing the required language field, see https://github.com/JamesHeinrich/getID3/issues/315 $frame_language = substr($parsedFrame['data'], $frame_offset, 3); $frame_offset += 3; $frame_terminatorpos = strpos($parsedFrame['data'], $frame_textencoding_terminator, $frame_offset); if (ord(substr($parsedFrame['data'], $frame_terminatorpos + strlen($frame_textencoding_terminator), 1)) === 0) { $frame_terminatorpos++; // strpos() fooled because 2nd byte of Unicode chars are often 0x00 } $parsedFrame['description'] = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); $parsedFrame['description'] = $this->MakeUTF16emptyStringEmpty($parsedFrame['description']); $parsedFrame['data'] = substr($parsedFrame['data'], $frame_terminatorpos + strlen($frame_textencoding_terminator)); $parsedFrame['data'] = $this->RemoveStringTerminator($parsedFrame['data'], $frame_textencoding_terminator); $parsedFrame['encodingid'] = $frame_textencoding; $parsedFrame['encoding'] = $this->TextEncodingNameLookup($frame_textencoding); $parsedFrame['language'] = $frame_language; $parsedFrame['languagename'] = $this->LanguageLookup($frame_language, false); if (!empty($parsedFrame['framenameshort']) && !empty($parsedFrame['data'])) { $info['id3v2']['comments'][$parsedFrame['framenameshort']][] = getid3_lib::iconv_fallback($parsedFrame['encoding'], $info['id3v2']['encoding'], $parsedFrame['data']); } } else { $this->warning('Invalid data in frame "'.$parsedFrame['frame_name'].'" at offset '.$parsedFrame['dataoffset']); } unset($parsedFrame['data']); } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'SYLT')) || // 4.9 SYLT Synchronised lyric/text (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'SLT'))) { // 4.10 SLT Synchronised lyric/text // There may be more than one 'SYLT' frame in each tag, // but only one with the same language and content descriptor. // <Header for 'Synchronised lyrics/text', ID: 'SYLT'> // Text encoding $xx // Language $xx xx xx // Time stamp format $xx // $01 (32-bit value) MPEG frames from beginning of file // $02 (32-bit value) milliseconds from beginning of file // Content type $xx // Content descriptor <text string according to encoding> $00 (00) // Terminated text to be synced (typically a syllable) // Sync identifier (terminator to above string) $00 (00) // Time stamp $xx (xx ...) $frame_offset = 0; $frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $frame_textencoding_terminator = $this->TextEncodingTerminatorLookup($frame_textencoding); if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) { $this->warning('Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding'); $frame_textencoding_terminator = "\x00"; } $frame_language = substr($parsedFrame['data'], $frame_offset, 3); $frame_offset += 3; $parsedFrame['timestampformat'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $parsedFrame['contenttypeid'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $parsedFrame['contenttype'] = $this->SYTLContentTypeLookup($parsedFrame['contenttypeid']); $parsedFrame['encodingid'] = $frame_textencoding; $parsedFrame['encoding'] = $this->TextEncodingNameLookup($frame_textencoding); $parsedFrame['language'] = $frame_language; $parsedFrame['languagename'] = $this->LanguageLookup($frame_language, false); $timestampindex = 0; $frame_remainingdata = substr($parsedFrame['data'], $frame_offset); while (strlen($frame_remainingdata)) { $frame_offset = 0; $frame_terminatorpos = strpos($frame_remainingdata, $frame_textencoding_terminator); if ($frame_terminatorpos === false) { $frame_remainingdata = ''; } else { if (ord(substr($frame_remainingdata, $frame_terminatorpos + strlen($frame_textencoding_terminator), 1)) === 0) { $frame_terminatorpos++; // strpos() fooled because 2nd byte of Unicode chars are often 0x00 } $parsedFrame['lyrics'][$timestampindex]['data'] = substr($frame_remainingdata, $frame_offset, $frame_terminatorpos - $frame_offset); $frame_remainingdata = substr($frame_remainingdata, $frame_terminatorpos + strlen($frame_textencoding_terminator)); if (($timestampindex == 0) && (ord($frame_remainingdata[0]) != 0)) { // timestamp probably omitted for first data item } else { $parsedFrame['lyrics'][$timestampindex]['timestamp'] = getid3_lib::BigEndian2Int(substr($frame_remainingdata, 0, 4)); $frame_remainingdata = substr($frame_remainingdata, 4); } $timestampindex++; } } unset($parsedFrame['data']); } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'COMM')) || // 4.10 COMM Comments (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'COM'))) { // 4.11 COM Comments // There may be more than one comment frame in each tag, // but only one with the same language and content descriptor. // <Header for 'Comment', ID: 'COMM'> // Text encoding $xx // Language $xx xx xx // Short content descrip. <text string according to encoding> $00 (00) // The actual text <full text string according to encoding> if (strlen($parsedFrame['data']) < 5) { $this->warning('Invalid data (too short) for "'.$parsedFrame['frame_name'].'" frame at offset '.$parsedFrame['dataoffset']); } else { $frame_offset = 0; $frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $frame_textencoding_terminator = $this->TextEncodingTerminatorLookup($frame_textencoding); if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) { $this->warning('Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding'); $frame_textencoding_terminator = "\x00"; } $frame_language = substr($parsedFrame['data'], $frame_offset, 3); $frame_offset += 3; $frame_terminatorpos = strpos($parsedFrame['data'], $frame_textencoding_terminator, $frame_offset); if (ord(substr($parsedFrame['data'], $frame_terminatorpos + strlen($frame_textencoding_terminator), 1)) === 0) { $frame_terminatorpos++; // strpos() fooled because 2nd byte of Unicode chars are often 0x00 } $parsedFrame['description'] = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); $parsedFrame['description'] = $this->MakeUTF16emptyStringEmpty($parsedFrame['description']); $frame_text = (string) substr($parsedFrame['data'], $frame_terminatorpos + strlen($frame_textencoding_terminator)); $frame_text = $this->RemoveStringTerminator($frame_text, $frame_textencoding_terminator); $parsedFrame['encodingid'] = $frame_textencoding; $parsedFrame['encoding'] = $this->TextEncodingNameLookup($frame_textencoding); $parsedFrame['language'] = $frame_language; $parsedFrame['languagename'] = $this->LanguageLookup($frame_language, false); $parsedFrame['data'] = $frame_text; if (!empty($parsedFrame['framenameshort']) && !empty($parsedFrame['data'])) { $commentkey = ($parsedFrame['description'] ? $parsedFrame['description'] : (!empty($info['id3v2']['comments'][$parsedFrame['framenameshort']]) ? count($info['id3v2']['comments'][$parsedFrame['framenameshort']]) : 0)); if (!isset($info['id3v2']['comments'][$parsedFrame['framenameshort']]) || !array_key_exists($commentkey, $info['id3v2']['comments'][$parsedFrame['framenameshort']])) { $info['id3v2']['comments'][$parsedFrame['framenameshort']][$commentkey] = getid3_lib::iconv_fallback($parsedFrame['encoding'], $info['id3v2']['encoding'], $parsedFrame['data']); } else { $info['id3v2']['comments'][$parsedFrame['framenameshort']][] = getid3_lib::iconv_fallback($parsedFrame['encoding'], $info['id3v2']['encoding'], $parsedFrame['data']); } } } } elseif (($id3v2_majorversion >= 4) && ($parsedFrame['frame_name'] == 'RVA2')) { // 4.11 RVA2 Relative volume adjustment (2) (ID3v2.4+ only) // There may be more than one 'RVA2' frame in each tag, // but only one with the same identification string // <Header for 'Relative volume adjustment (2)', ID: 'RVA2'> // Identification <text string> $00 // The 'identification' string is used to identify the situation and/or // device where this adjustment should apply. The following is then // repeated for every channel: // Type of channel $xx // Volume adjustment $xx xx // Bits representing peak $xx // Peak volume $xx (xx ...) $frame_terminatorpos = strpos($parsedFrame['data'], "\x00"); $frame_idstring = substr($parsedFrame['data'], 0, $frame_terminatorpos); if (ord($frame_idstring) === 0) { $frame_idstring = ''; } $frame_remainingdata = substr($parsedFrame['data'], $frame_terminatorpos + strlen("\x00")); $parsedFrame['description'] = $frame_idstring; $RVA2channelcounter = 0; while (strlen($frame_remainingdata) >= 5) { $frame_offset = 0; $frame_channeltypeid = ord(substr($frame_remainingdata, $frame_offset++, 1)); $parsedFrame[$RVA2channelcounter]['channeltypeid'] = $frame_channeltypeid; $parsedFrame[$RVA2channelcounter]['channeltype'] = $this->RVA2ChannelTypeLookup($frame_channeltypeid); $parsedFrame[$RVA2channelcounter]['volumeadjust'] = getid3_lib::BigEndian2Int(substr($frame_remainingdata, $frame_offset, 2), false, true); // 16-bit signed $frame_offset += 2; $parsedFrame[$RVA2channelcounter]['bitspeakvolume'] = ord(substr($frame_remainingdata, $frame_offset++, 1)); if (($parsedFrame[$RVA2channelcounter]['bitspeakvolume'] < 1) || ($parsedFrame[$RVA2channelcounter]['bitspeakvolume'] > 4)) { $this->warning('ID3v2::RVA2 frame['.$RVA2channelcounter.'] contains invalid '.$parsedFrame[$RVA2channelcounter]['bitspeakvolume'].'-byte bits-representing-peak value'); break; } $frame_bytespeakvolume = ceil($parsedFrame[$RVA2channelcounter]['bitspeakvolume'] / 8); $parsedFrame[$RVA2channelcounter]['peakvolume'] = getid3_lib::BigEndian2Int(substr($frame_remainingdata, $frame_offset, $frame_bytespeakvolume)); $frame_remainingdata = substr($frame_remainingdata, $frame_offset + $frame_bytespeakvolume); $RVA2channelcounter++; } unset($parsedFrame['data']); } elseif ((($id3v2_majorversion == 3) && ($parsedFrame['frame_name'] == 'RVAD')) || // 4.12 RVAD Relative volume adjustment (ID3v2.3 only) (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'RVA'))) { // 4.12 RVA Relative volume adjustment (ID3v2.2 only) // There may only be one 'RVA' frame in each tag // <Header for 'Relative volume adjustment', ID: 'RVA'> // ID3v2.2 => Increment/decrement %000000ba // ID3v2.3 => Increment/decrement %00fedcba // Bits used for volume descr. $xx // Relative volume change, right $xx xx (xx ...) // a // Relative volume change, left $xx xx (xx ...) // b // Peak volume right $xx xx (xx ...) // Peak volume left $xx xx (xx ...) // ID3v2.3 only, optional (not present in ID3v2.2): // Relative volume change, right back $xx xx (xx ...) // c // Relative volume change, left back $xx xx (xx ...) // d // Peak volume right back $xx xx (xx ...) // Peak volume left back $xx xx (xx ...) // ID3v2.3 only, optional (not present in ID3v2.2): // Relative volume change, center $xx xx (xx ...) // e // Peak volume center $xx xx (xx ...) // ID3v2.3 only, optional (not present in ID3v2.2): // Relative volume change, bass $xx xx (xx ...) // f // Peak volume bass $xx xx (xx ...) $frame_offset = 0; $frame_incrdecrflags = getid3_lib::BigEndian2Bin(substr($parsedFrame['data'], $frame_offset++, 1)); $parsedFrame['incdec']['right'] = (bool) substr($frame_incrdecrflags, 6, 1); $parsedFrame['incdec']['left'] = (bool) substr($frame_incrdecrflags, 7, 1); $parsedFrame['bitsvolume'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $frame_bytesvolume = ceil($parsedFrame['bitsvolume'] / 8); $parsedFrame['volumechange']['right'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume)); if ($parsedFrame['incdec']['right'] === false) { $parsedFrame['volumechange']['right'] *= -1; } $frame_offset += $frame_bytesvolume; $parsedFrame['volumechange']['left'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume)); if ($parsedFrame['incdec']['left'] === false) { $parsedFrame['volumechange']['left'] *= -1; } $frame_offset += $frame_bytesvolume; $parsedFrame['peakvolume']['right'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume)); $frame_offset += $frame_bytesvolume; $parsedFrame['peakvolume']['left'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume)); $frame_offset += $frame_bytesvolume; if ($id3v2_majorversion == 3) { $parsedFrame['data'] = substr($parsedFrame['data'], $frame_offset); if (strlen($parsedFrame['data']) > 0) { $parsedFrame['incdec']['rightrear'] = (bool) substr($frame_incrdecrflags, 4, 1); $parsedFrame['incdec']['leftrear'] = (bool) substr($frame_incrdecrflags, 5, 1); $parsedFrame['volumechange']['rightrear'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume)); if ($parsedFrame['incdec']['rightrear'] === false) { $parsedFrame['volumechange']['rightrear'] *= -1; } $frame_offset += $frame_bytesvolume; $parsedFrame['volumechange']['leftrear'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume)); if ($parsedFrame['incdec']['leftrear'] === false) { $parsedFrame['volumechange']['leftrear'] *= -1; } $frame_offset += $frame_bytesvolume; $parsedFrame['peakvolume']['rightrear'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume)); $frame_offset += $frame_bytesvolume; $parsedFrame['peakvolume']['leftrear'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume)); $frame_offset += $frame_bytesvolume; } $parsedFrame['data'] = substr($parsedFrame['data'], $frame_offset); if (strlen($parsedFrame['data']) > 0) { $parsedFrame['incdec']['center'] = (bool) substr($frame_incrdecrflags, 3, 1); $parsedFrame['volumechange']['center'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume)); if ($parsedFrame['incdec']['center'] === false) { $parsedFrame['volumechange']['center'] *= -1; } $frame_offset += $frame_bytesvolume; $parsedFrame['peakvolume']['center'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume)); $frame_offset += $frame_bytesvolume; } $parsedFrame['data'] = substr($parsedFrame['data'], $frame_offset); if (strlen($parsedFrame['data']) > 0) { $parsedFrame['incdec']['bass'] = (bool) substr($frame_incrdecrflags, 2, 1); $parsedFrame['volumechange']['bass'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume)); if ($parsedFrame['incdec']['bass'] === false) { $parsedFrame['volumechange']['bass'] *= -1; } $frame_offset += $frame_bytesvolume; $parsedFrame['peakvolume']['bass'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume)); $frame_offset += $frame_bytesvolume; } } unset($parsedFrame['data']); } elseif (($id3v2_majorversion >= 4) && ($parsedFrame['frame_name'] == 'EQU2')) { // 4.12 EQU2 Equalisation (2) (ID3v2.4+ only) // There may be more than one 'EQU2' frame in each tag, // but only one with the same identification string // <Header of 'Equalisation (2)', ID: 'EQU2'> // Interpolation method $xx // $00 Band // $01 Linear // Identification <text string> $00 // The following is then repeated for every adjustment point // Frequency $xx xx // Volume adjustment $xx xx $frame_offset = 0; $frame_interpolationmethod = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $frame_terminatorpos = strpos($parsedFrame['data'], "\x00", $frame_offset); $frame_idstring = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); if (ord($frame_idstring) === 0) { $frame_idstring = ''; } $parsedFrame['description'] = $frame_idstring; $frame_remainingdata = substr($parsedFrame['data'], $frame_terminatorpos + strlen("\x00")); while (strlen($frame_remainingdata)) { $frame_frequency = getid3_lib::BigEndian2Int(substr($frame_remainingdata, 0, 2)) / 2; $parsedFrame['data'][$frame_frequency] = getid3_lib::BigEndian2Int(substr($frame_remainingdata, 2, 2), false, true); $frame_remainingdata = substr($frame_remainingdata, 4); } $parsedFrame['interpolationmethod'] = $frame_interpolationmethod; unset($parsedFrame['data']); } elseif ((($id3v2_majorversion == 3) && ($parsedFrame['frame_name'] == 'EQUA')) || // 4.12 EQUA Equalisation (ID3v2.3 only) (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'EQU'))) { // 4.13 EQU Equalisation (ID3v2.2 only) // There may only be one 'EQUA' frame in each tag // <Header for 'Relative volume adjustment', ID: 'EQU'> // Adjustment bits $xx // This is followed by 2 bytes + ('adjustment bits' rounded up to the // nearest byte) for every equalisation band in the following format, // giving a frequency range of 0 - 32767Hz: // Increment/decrement %x (MSB of the Frequency) // Frequency (lower 15 bits) // Adjustment $xx (xx ...) $frame_offset = 0; $parsedFrame['adjustmentbits'] = substr($parsedFrame['data'], $frame_offset++, 1); $frame_adjustmentbytes = ceil($parsedFrame['adjustmentbits'] / 8); $frame_remainingdata = (string) substr($parsedFrame['data'], $frame_offset); while (strlen($frame_remainingdata) > 0) { $frame_frequencystr = getid3_lib::BigEndian2Bin(substr($frame_remainingdata, 0, 2)); $frame_incdec = (bool) substr($frame_frequencystr, 0, 1); $frame_frequency = bindec(substr($frame_frequencystr, 1, 15)); $parsedFrame[$frame_frequency]['incdec'] = $frame_incdec; $parsedFrame[$frame_frequency]['adjustment'] = getid3_lib::BigEndian2Int(substr($frame_remainingdata, 2, $frame_adjustmentbytes)); if ($parsedFrame[$frame_frequency]['incdec'] === false) { $parsedFrame[$frame_frequency]['adjustment'] *= -1; } $frame_remainingdata = substr($frame_remainingdata, 2 + $frame_adjustmentbytes); } unset($parsedFrame['data']); } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'RVRB')) || // 4.13 RVRB Reverb (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'REV'))) { // 4.14 REV Reverb // There may only be one 'RVRB' frame in each tag. // <Header for 'Reverb', ID: 'RVRB'> // Reverb left (ms) $xx xx // Reverb right (ms) $xx xx // Reverb bounces, left $xx // Reverb bounces, right $xx // Reverb feedback, left to left $xx // Reverb feedback, left to right $xx // Reverb feedback, right to right $xx // Reverb feedback, right to left $xx // Premix left to right $xx // Premix right to left $xx $frame_offset = 0; $parsedFrame['left'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 2)); $frame_offset += 2; $parsedFrame['right'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 2)); $frame_offset += 2; $parsedFrame['bouncesL'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $parsedFrame['bouncesR'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $parsedFrame['feedbackLL'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $parsedFrame['feedbackLR'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $parsedFrame['feedbackRR'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $parsedFrame['feedbackRL'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $parsedFrame['premixLR'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $parsedFrame['premixRL'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); unset($parsedFrame['data']); } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'APIC')) || // 4.14 APIC Attached picture (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'PIC'))) { // 4.15 PIC Attached picture // There may be several pictures attached to one file, // each in their individual 'APIC' frame, but only one // with the same content descriptor // <Header for 'Attached picture', ID: 'APIC'> // Text encoding $xx // ID3v2.3+ => MIME type <text string> $00 // ID3v2.2 => Image format $xx xx xx // Picture type $xx // Description <text string according to encoding> $00 (00) // Picture data <binary data> $frame_offset = 0; $frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $frame_textencoding_terminator = $this->TextEncodingTerminatorLookup($frame_textencoding); if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) { $this->warning('Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding'); $frame_textencoding_terminator = "\x00"; } $frame_imagetype = null; $frame_mimetype = null; if ($id3v2_majorversion == 2 && strlen($parsedFrame['data']) > $frame_offset) { $frame_imagetype = substr($parsedFrame['data'], $frame_offset, 3); if (strtolower($frame_imagetype) == 'ima') { // complete hack for mp3Rage (www.chaoticsoftware.com) that puts ID3v2.3-formatted // MIME type instead of 3-char ID3v2.2-format image type (thanks xbhoffØpacbell*net) $frame_terminatorpos = strpos($parsedFrame['data'], "\x00", $frame_offset); $frame_mimetype = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); if (ord($frame_mimetype) === 0) { $frame_mimetype = ''; } $frame_imagetype = strtoupper(str_replace('image/', '', strtolower($frame_mimetype))); if ($frame_imagetype == 'JPEG') { $frame_imagetype = 'JPG'; } $frame_offset = $frame_terminatorpos + strlen("\x00"); } else { $frame_offset += 3; } } if ($id3v2_majorversion > 2 && strlen($parsedFrame['data']) > $frame_offset) { $frame_terminatorpos = strpos($parsedFrame['data'], "\x00", $frame_offset); $frame_mimetype = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); if (ord($frame_mimetype) === 0) { $frame_mimetype = ''; } $frame_offset = $frame_terminatorpos + strlen("\x00"); } $frame_picturetype = ord(substr($parsedFrame['data'], $frame_offset++, 1)); if ($frame_offset >= $parsedFrame['datalength']) { $this->warning('data portion of APIC frame is missing at offset '.($parsedFrame['dataoffset'] + 8 + $frame_offset)); } else { $frame_terminatorpos = strpos($parsedFrame['data'], $frame_textencoding_terminator, $frame_offset); if (ord(substr($parsedFrame['data'], $frame_terminatorpos + strlen($frame_textencoding_terminator), 1)) === 0) { $frame_terminatorpos++; // strpos() fooled because 2nd byte of Unicode chars are often 0x00 } $parsedFrame['description'] = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); $parsedFrame['description'] = $this->MakeUTF16emptyStringEmpty($parsedFrame['description']); $parsedFrame['encodingid'] = $frame_textencoding; $parsedFrame['encoding'] = $this->TextEncodingNameLookup($frame_textencoding); if ($id3v2_majorversion == 2) { $parsedFrame['imagetype'] = isset($frame_imagetype) ? $frame_imagetype : null; } else { $parsedFrame['mime'] = isset($frame_mimetype) ? $frame_mimetype : null; } $parsedFrame['picturetypeid'] = $frame_picturetype; $parsedFrame['picturetype'] = $this->APICPictureTypeLookup($frame_picturetype); $parsedFrame['data'] = substr($parsedFrame['data'], $frame_terminatorpos + strlen($frame_textencoding_terminator)); $parsedFrame['datalength'] = strlen($parsedFrame['data']); $parsedFrame['image_mime'] = ''; $imageinfo = array(); if ($imagechunkcheck = getid3_lib::GetDataImageSize($parsedFrame['data'], $imageinfo)) { if (($imagechunkcheck[2] >= 1) && ($imagechunkcheck[2] <= 3)) { $parsedFrame['image_mime'] = image_type_to_mime_type($imagechunkcheck[2]); if ($imagechunkcheck[0]) { $parsedFrame['image_width'] = $imagechunkcheck[0]; } if ($imagechunkcheck[1]) { $parsedFrame['image_height'] = $imagechunkcheck[1]; } } } do { if ($this->getid3->option_save_attachments === false) { // skip entirely unset($parsedFrame['data']); break; } $dir = ''; if ($this->getid3->option_save_attachments === true) { // great /* } elseif (is_int($this->getid3->option_save_attachments)) { if ($this->getid3->option_save_attachments < $parsedFrame['data_length']) { // too big, skip $this->warning('attachment at '.$frame_offset.' is too large to process inline ('.number_format($parsedFrame['data_length']).' bytes)'); unset($parsedFrame['data']); break; } */ } elseif (is_string($this->getid3->option_save_attachments)) { $dir = rtrim(str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $this->getid3->option_save_attachments), DIRECTORY_SEPARATOR); if (!is_dir($dir) || !getID3::is_writable($dir)) { // cannot write, skip $this->warning('attachment at '.$frame_offset.' cannot be saved to "'.$dir.'" (not writable)'); unset($parsedFrame['data']); break; } } // if we get this far, must be OK if (is_string($this->getid3->option_save_attachments)) { $destination_filename = $dir.DIRECTORY_SEPARATOR.md5($info['filenamepath']).'_'.$frame_offset; if (!file_exists($destination_filename) || getID3::is_writable($destination_filename)) { file_put_contents($destination_filename, $parsedFrame['data']); } else { $this->warning('attachment at '.$frame_offset.' cannot be saved to "'.$destination_filename.'" (not writable)'); } $parsedFrame['data_filename'] = $destination_filename; unset($parsedFrame['data']); } else { if (!empty($parsedFrame['framenameshort']) && !empty($parsedFrame['data'])) { if (!isset($info['id3v2']['comments']['picture'])) { $info['id3v2']['comments']['picture'] = array(); } $comments_picture_data = array(); foreach (array('data', 'image_mime', 'image_width', 'image_height', 'imagetype', 'picturetype', 'description', 'datalength') as $picture_key) { if (isset($parsedFrame[$picture_key])) { $comments_picture_data[$picture_key] = $parsedFrame[$picture_key]; } } $info['id3v2']['comments']['picture'][] = $comments_picture_data; unset($comments_picture_data); } } } while (false); // @phpstan-ignore-line } } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'GEOB')) || // 4.15 GEOB General encapsulated object (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'GEO'))) { // 4.16 GEO General encapsulated object // There may be more than one 'GEOB' frame in each tag, // but only one with the same content descriptor // <Header for 'General encapsulated object', ID: 'GEOB'> // Text encoding $xx // MIME type <text string> $00 // Filename <text string according to encoding> $00 (00) // Content description <text string according to encoding> $00 (00) // Encapsulated object <binary data> $frame_offset = 0; $frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $frame_textencoding_terminator = $this->TextEncodingTerminatorLookup($frame_textencoding); if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) { $this->warning('Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding'); $frame_textencoding_terminator = "\x00"; } $frame_terminatorpos = strpos($parsedFrame['data'], "\x00", $frame_offset); $frame_mimetype = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); if (ord($frame_mimetype) === 0) { $frame_mimetype = ''; } $frame_offset = $frame_terminatorpos + strlen("\x00"); $frame_terminatorpos = strpos($parsedFrame['data'], $frame_textencoding_terminator, $frame_offset); if (ord(substr($parsedFrame['data'], $frame_terminatorpos + strlen($frame_textencoding_terminator), 1)) === 0) { $frame_terminatorpos++; // strpos() fooled because 2nd byte of Unicode chars are often 0x00 } $frame_filename = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); if (ord($frame_filename) === 0) { $frame_filename = ''; } $frame_offset = $frame_terminatorpos + strlen($frame_textencoding_terminator); $frame_terminatorpos = strpos($parsedFrame['data'], $frame_textencoding_terminator, $frame_offset); if (ord(substr($parsedFrame['data'], $frame_terminatorpos + strlen($frame_textencoding_terminator), 1)) === 0) { $frame_terminatorpos++; // strpos() fooled because 2nd byte of Unicode chars are often 0x00 } $parsedFrame['description'] = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); $parsedFrame['description'] = $this->MakeUTF16emptyStringEmpty($parsedFrame['description']); $frame_offset = $frame_terminatorpos + strlen($frame_textencoding_terminator); $parsedFrame['objectdata'] = (string) substr($parsedFrame['data'], $frame_offset); $parsedFrame['encodingid'] = $frame_textencoding; $parsedFrame['encoding'] = $this->TextEncodingNameLookup($frame_textencoding); $parsedFrame['mime'] = $frame_mimetype; $parsedFrame['filename'] = $frame_filename; unset($parsedFrame['data']); } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'PCNT')) || // 4.16 PCNT Play counter (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'CNT'))) { // 4.17 CNT Play counter // There may only be one 'PCNT' frame in each tag. // When the counter reaches all one's, one byte is inserted in // front of the counter thus making the counter eight bits bigger // <Header for 'Play counter', ID: 'PCNT'> // Counter $xx xx xx xx (xx ...) $parsedFrame['data'] = getid3_lib::BigEndian2Int($parsedFrame['data']); } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'POPM')) || // 4.17 POPM Popularimeter (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'POP'))) { // 4.18 POP Popularimeter // There may be more than one 'POPM' frame in each tag, // but only one with the same email address // <Header for 'Popularimeter', ID: 'POPM'> // Email to user <text string> $00 // Rating $xx // Counter $xx xx xx xx (xx ...) $frame_offset = 0; $frame_terminatorpos = strpos($parsedFrame['data'], "\x00", $frame_offset); $frame_emailaddress = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); if (ord($frame_emailaddress) === 0) { $frame_emailaddress = ''; } $frame_offset = $frame_terminatorpos + strlen("\x00"); $frame_rating = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $parsedFrame['counter'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset)); $parsedFrame['email'] = $frame_emailaddress; $parsedFrame['rating'] = $frame_rating; unset($parsedFrame['data']); } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'RBUF')) || // 4.18 RBUF Recommended buffer size (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'BUF'))) { // 4.19 BUF Recommended buffer size // There may only be one 'RBUF' frame in each tag // <Header for 'Recommended buffer size', ID: 'RBUF'> // Buffer size $xx xx xx // Embedded info flag %0000000x // Offset to next tag $xx xx xx xx $frame_offset = 0; $parsedFrame['buffersize'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 3)); $frame_offset += 3; $frame_embeddedinfoflags = getid3_lib::BigEndian2Bin(substr($parsedFrame['data'], $frame_offset++, 1)); $parsedFrame['flags']['embededinfo'] = (bool) substr($frame_embeddedinfoflags, 7, 1); $parsedFrame['nexttagoffset'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 4)); unset($parsedFrame['data']); } elseif (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'CRM')) { // 4.20 Encrypted meta frame (ID3v2.2 only) // There may be more than one 'CRM' frame in a tag, // but only one with the same 'owner identifier' // <Header for 'Encrypted meta frame', ID: 'CRM'> // Owner identifier <textstring> $00 (00) // Content/explanation <textstring> $00 (00) // Encrypted datablock <binary data> $frame_offset = 0; $frame_terminatorpos = strpos($parsedFrame['data'], "\x00", $frame_offset); $frame_ownerid = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); $frame_offset = $frame_terminatorpos + strlen("\x00"); $frame_terminatorpos = strpos($parsedFrame['data'], "\x00", $frame_offset); $parsedFrame['description'] = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); $parsedFrame['description'] = $this->MakeUTF16emptyStringEmpty($parsedFrame['description']); $frame_offset = $frame_terminatorpos + strlen("\x00"); $parsedFrame['ownerid'] = $frame_ownerid; $parsedFrame['data'] = (string) substr($parsedFrame['data'], $frame_offset); unset($parsedFrame['data']); } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'AENC')) || // 4.19 AENC Audio encryption (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'CRA'))) { // 4.21 CRA Audio encryption // There may be more than one 'AENC' frames in a tag, // but only one with the same 'Owner identifier' // <Header for 'Audio encryption', ID: 'AENC'> // Owner identifier <text string> $00 // Preview start $xx xx // Preview length $xx xx // Encryption info <binary data> $frame_offset = 0; $frame_terminatorpos = strpos($parsedFrame['data'], "\x00", $frame_offset); $frame_ownerid = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); if (ord($frame_ownerid) === 0) { $frame_ownerid = ''; } $frame_offset = $frame_terminatorpos + strlen("\x00"); $parsedFrame['ownerid'] = $frame_ownerid; $parsedFrame['previewstart'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 2)); $frame_offset += 2; $parsedFrame['previewlength'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 2)); $frame_offset += 2; $parsedFrame['encryptioninfo'] = (string) substr($parsedFrame['data'], $frame_offset); unset($parsedFrame['data']); } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'LINK')) || // 4.20 LINK Linked information (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'LNK'))) { // 4.22 LNK Linked information // There may be more than one 'LINK' frame in a tag, // but only one with the same contents // <Header for 'Linked information', ID: 'LINK'> // ID3v2.3+ => Frame identifier $xx xx xx xx // ID3v2.2 => Frame identifier $xx xx xx // URL <text string> $00 // ID and additional data <text string(s)> $frame_offset = 0; if ($id3v2_majorversion == 2) { $parsedFrame['frameid'] = substr($parsedFrame['data'], $frame_offset, 3); $frame_offset += 3; } else { $parsedFrame['frameid'] = substr($parsedFrame['data'], $frame_offset, 4); $frame_offset += 4; } $frame_terminatorpos = strpos($parsedFrame['data'], "\x00", $frame_offset); $frame_url = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); if (ord($frame_url) === 0) { $frame_url = ''; } $frame_offset = $frame_terminatorpos + strlen("\x00"); $parsedFrame['url'] = $frame_url; $parsedFrame['additionaldata'] = (string) substr($parsedFrame['data'], $frame_offset); if (!empty($parsedFrame['framenameshort']) && $parsedFrame['url']) { $info['id3v2']['comments'][$parsedFrame['framenameshort']][] = getid3_lib::iconv_fallback_iso88591_utf8($parsedFrame['url']); } unset($parsedFrame['data']); } elseif (($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'POSS')) { // 4.21 POSS Position synchronisation frame (ID3v2.3+ only) // There may only be one 'POSS' frame in each tag // <Head for 'Position synchronisation', ID: 'POSS'> // Time stamp format $xx // Position $xx (xx ...) $frame_offset = 0; $parsedFrame['timestampformat'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $parsedFrame['position'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset)); unset($parsedFrame['data']); } elseif (($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'USER')) { // 4.22 USER Terms of use (ID3v2.3+ only) // There may be more than one 'Terms of use' frame in a tag, // but only one with the same 'Language' // <Header for 'Terms of use frame', ID: 'USER'> // Text encoding $xx // Language $xx xx xx // The actual text <text string according to encoding> $frame_offset = 0; $frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1)); if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) { $this->warning('Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding'); } $frame_language = substr($parsedFrame['data'], $frame_offset, 3); $frame_offset += 3; $parsedFrame['language'] = $frame_language; $parsedFrame['languagename'] = $this->LanguageLookup($frame_language, false); $parsedFrame['encodingid'] = $frame_textencoding; $parsedFrame['encoding'] = $this->TextEncodingNameLookup($frame_textencoding); $parsedFrame['data'] = (string) substr($parsedFrame['data'], $frame_offset); $parsedFrame['data'] = $this->RemoveStringTerminator($parsedFrame['data'], $this->TextEncodingTerminatorLookup($frame_textencoding)); if (!empty($parsedFrame['framenameshort']) && !empty($parsedFrame['data'])) { $info['id3v2']['comments'][$parsedFrame['framenameshort']][] = getid3_lib::iconv_fallback($parsedFrame['encoding'], $info['id3v2']['encoding'], $parsedFrame['data']); } unset($parsedFrame['data']); } elseif (($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'OWNE')) { // 4.23 OWNE Ownership frame (ID3v2.3+ only) // There may only be one 'OWNE' frame in a tag // <Header for 'Ownership frame', ID: 'OWNE'> // Text encoding $xx // Price paid <text string> $00 // Date of purch. <text string> // Seller <text string according to encoding> $frame_offset = 0; $frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1)); if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) { $this->warning('Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding'); } $parsedFrame['encodingid'] = $frame_textencoding; $parsedFrame['encoding'] = $this->TextEncodingNameLookup($frame_textencoding); $frame_terminatorpos = strpos($parsedFrame['data'], "\x00", $frame_offset); $frame_pricepaid = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); $frame_offset = $frame_terminatorpos + strlen("\x00"); $parsedFrame['pricepaid']['currencyid'] = substr($frame_pricepaid, 0, 3); $parsedFrame['pricepaid']['currency'] = $this->LookupCurrencyUnits($parsedFrame['pricepaid']['currencyid']); $parsedFrame['pricepaid']['value'] = substr($frame_pricepaid, 3); $parsedFrame['purchasedate'] = substr($parsedFrame['data'], $frame_offset, 8); if ($this->IsValidDateStampString($parsedFrame['purchasedate'])) { $parsedFrame['purchasedateunix'] = mktime (0, 0, 0, substr($parsedFrame['purchasedate'], 4, 2), substr($parsedFrame['purchasedate'], 6, 2), substr($parsedFrame['purchasedate'], 0, 4)); } $frame_offset += 8; $parsedFrame['seller'] = (string) substr($parsedFrame['data'], $frame_offset); $parsedFrame['seller'] = $this->RemoveStringTerminator($parsedFrame['seller'], $this->TextEncodingTerminatorLookup($frame_textencoding)); unset($parsedFrame['data']); } elseif (($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'COMR')) { // 4.24 COMR Commercial frame (ID3v2.3+ only) // There may be more than one 'commercial frame' in a tag, // but no two may be identical // <Header for 'Commercial frame', ID: 'COMR'> // Text encoding $xx // Price string <text string> $00 // Valid until <text string> // Contact URL <text string> $00 // Received as $xx // Name of seller <text string according to encoding> $00 (00) // Description <text string according to encoding> $00 (00) // Picture MIME type <string> $00 // Seller logo <binary data> $frame_offset = 0; $frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $frame_textencoding_terminator = $this->TextEncodingTerminatorLookup($frame_textencoding); if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) { $this->warning('Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding'); $frame_textencoding_terminator = "\x00"; } $frame_terminatorpos = strpos($parsedFrame['data'], "\x00", $frame_offset); $frame_pricestring = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); $frame_offset = $frame_terminatorpos + strlen("\x00"); $frame_rawpricearray = explode('/', $frame_pricestring); foreach ($frame_rawpricearray as $key => $val) { $frame_currencyid = substr($val, 0, 3); $parsedFrame['price'][$frame_currencyid]['currency'] = $this->LookupCurrencyUnits($frame_currencyid); $parsedFrame['price'][$frame_currencyid]['value'] = substr($val, 3); } $frame_datestring = substr($parsedFrame['data'], $frame_offset, 8); $frame_offset += 8; $frame_terminatorpos = strpos($parsedFrame['data'], "\x00", $frame_offset); $frame_contacturl = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); $frame_offset = $frame_terminatorpos + strlen("\x00"); $frame_receivedasid = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $frame_terminatorpos = strpos($parsedFrame['data'], $frame_textencoding_terminator, $frame_offset); if (ord(substr($parsedFrame['data'], $frame_terminatorpos + strlen($frame_textencoding_terminator), 1)) === 0) { $frame_terminatorpos++; // strpos() fooled because 2nd byte of Unicode chars are often 0x00 } $frame_sellername = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); if (ord($frame_sellername) === 0) { $frame_sellername = ''; } $frame_offset = $frame_terminatorpos + strlen($frame_textencoding_terminator); $frame_terminatorpos = strpos($parsedFrame['data'], $frame_textencoding_terminator, $frame_offset); if (ord(substr($parsedFrame['data'], $frame_terminatorpos + strlen($frame_textencoding_terminator), 1)) === 0) { $frame_terminatorpos++; // strpos() fooled because 2nd byte of Unicode chars are often 0x00 } $parsedFrame['description'] = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); $parsedFrame['description'] = $this->MakeUTF16emptyStringEmpty($parsedFrame['description']); $frame_offset = $frame_terminatorpos + strlen($frame_textencoding_terminator); $frame_terminatorpos = strpos($parsedFrame['data'], "\x00", $frame_offset); $frame_mimetype = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); $frame_offset = $frame_terminatorpos + strlen("\x00"); $frame_sellerlogo = substr($parsedFrame['data'], $frame_offset); $parsedFrame['encodingid'] = $frame_textencoding; $parsedFrame['encoding'] = $this->TextEncodingNameLookup($frame_textencoding); $parsedFrame['pricevaliduntil'] = $frame_datestring; $parsedFrame['contacturl'] = $frame_contacturl; $parsedFrame['receivedasid'] = $frame_receivedasid; $parsedFrame['receivedas'] = $this->COMRReceivedAsLookup($frame_receivedasid); $parsedFrame['sellername'] = $frame_sellername; $parsedFrame['mime'] = $frame_mimetype; $parsedFrame['logo'] = $frame_sellerlogo; unset($parsedFrame['data']); } elseif (($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'ENCR')) { // 4.25 ENCR Encryption method registration (ID3v2.3+ only) // There may be several 'ENCR' frames in a tag, // but only one containing the same symbol // and only one containing the same owner identifier // <Header for 'Encryption method registration', ID: 'ENCR'> // Owner identifier <text string> $00 // Method symbol $xx // Encryption data <binary data> $frame_offset = 0; $frame_terminatorpos = strpos($parsedFrame['data'], "\x00", $frame_offset); $frame_ownerid = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); if (ord($frame_ownerid) === 0) { $frame_ownerid = ''; } $frame_offset = $frame_terminatorpos + strlen("\x00"); $parsedFrame['ownerid'] = $frame_ownerid; $parsedFrame['methodsymbol'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $parsedFrame['data'] = (string) substr($parsedFrame['data'], $frame_offset); } elseif (($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'GRID')) { // 4.26 GRID Group identification registration (ID3v2.3+ only) // There may be several 'GRID' frames in a tag, // but only one containing the same symbol // and only one containing the same owner identifier // <Header for 'Group ID registration', ID: 'GRID'> // Owner identifier <text string> $00 // Group symbol $xx // Group dependent data <binary data> $frame_offset = 0; $frame_terminatorpos = strpos($parsedFrame['data'], "\x00", $frame_offset); $frame_ownerid = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); if (ord($frame_ownerid) === 0) { $frame_ownerid = ''; } $frame_offset = $frame_terminatorpos + strlen("\x00"); $parsedFrame['ownerid'] = $frame_ownerid; $parsedFrame['groupsymbol'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $parsedFrame['data'] = (string) substr($parsedFrame['data'], $frame_offset); } elseif (($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'PRIV')) { // 4.27 PRIV Private frame (ID3v2.3+ only) // The tag may contain more than one 'PRIV' frame // but only with different contents // <Header for 'Private frame', ID: 'PRIV'> // Owner identifier <text string> $00 // The private data <binary data> $frame_offset = 0; $frame_terminatorpos = strpos($parsedFrame['data'], "\x00", $frame_offset); $frame_ownerid = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); if (ord($frame_ownerid) === 0) { $frame_ownerid = ''; } $frame_offset = $frame_terminatorpos + strlen("\x00"); $parsedFrame['ownerid'] = $frame_ownerid; $parsedFrame['data'] = (string) substr($parsedFrame['data'], $frame_offset); } elseif (($id3v2_majorversion >= 4) && ($parsedFrame['frame_name'] == 'SIGN')) { // 4.28 SIGN Signature frame (ID3v2.4+ only) // There may be more than one 'signature frame' in a tag, // but no two may be identical // <Header for 'Signature frame', ID: 'SIGN'> // Group symbol $xx // Signature <binary data> $frame_offset = 0; $parsedFrame['groupsymbol'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $parsedFrame['data'] = (string) substr($parsedFrame['data'], $frame_offset); } elseif (($id3v2_majorversion >= 4) && ($parsedFrame['frame_name'] == 'SEEK')) { // 4.29 SEEK Seek frame (ID3v2.4+ only) // There may only be one 'seek frame' in a tag // <Header for 'Seek frame', ID: 'SEEK'> // Minimum offset to next tag $xx xx xx xx $frame_offset = 0; $parsedFrame['data'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 4)); } elseif (($id3v2_majorversion >= 4) && ($parsedFrame['frame_name'] == 'ASPI')) { // 4.30 ASPI Audio seek point index (ID3v2.4+ only) // There may only be one 'audio seek point index' frame in a tag // <Header for 'Seek Point Index', ID: 'ASPI'> // Indexed data start (S) $xx xx xx xx // Indexed data length (L) $xx xx xx xx // Number of index points (N) $xx xx // Bits per index point (b) $xx // Then for every index point the following data is included: // Fraction at index (Fi) $xx (xx) $frame_offset = 0; $parsedFrame['datastart'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 4)); $frame_offset += 4; $parsedFrame['indexeddatalength'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 4)); $frame_offset += 4; $parsedFrame['indexpoints'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 2)); $frame_offset += 2; $parsedFrame['bitsperpoint'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $frame_bytesperpoint = ceil($parsedFrame['bitsperpoint'] / 8); for ($i = 0; $i < $parsedFrame['indexpoints']; $i++) { $parsedFrame['indexes'][$i] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesperpoint)); $frame_offset += $frame_bytesperpoint; } unset($parsedFrame['data']); } elseif (($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'RGAD')) { // Replay Gain Adjustment // http://privatewww.essex.ac.uk/~djmrob/replaygain/file_format_id3v2.html // There may only be one 'RGAD' frame in a tag // <Header for 'Replay Gain Adjustment', ID: 'RGAD'> // Peak Amplitude $xx $xx $xx $xx // Radio Replay Gain Adjustment %aaabbbcd %dddddddd // Audiophile Replay Gain Adjustment %aaabbbcd %dddddddd // a - name code // b - originator code // c - sign bit // d - replay gain adjustment $frame_offset = 0; $parsedFrame['peakamplitude'] = getid3_lib::BigEndian2Float(substr($parsedFrame['data'], $frame_offset, 4)); $frame_offset += 4; foreach (array('track','album') as $rgad_entry_type) { $rg_adjustment_word = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 2)); $frame_offset += 2; $parsedFrame['raw'][$rgad_entry_type]['name'] = ($rg_adjustment_word & 0xE000) >> 13; $parsedFrame['raw'][$rgad_entry_type]['originator'] = ($rg_adjustment_word & 0x1C00) >> 10; $parsedFrame['raw'][$rgad_entry_type]['signbit'] = ($rg_adjustment_word & 0x0200) >> 9; $parsedFrame['raw'][$rgad_entry_type]['adjustment'] = ($rg_adjustment_word & 0x0100); } $parsedFrame['track']['name'] = getid3_lib::RGADnameLookup($parsedFrame['raw']['track']['name']); $parsedFrame['track']['originator'] = getid3_lib::RGADoriginatorLookup($parsedFrame['raw']['track']['originator']); $parsedFrame['track']['adjustment'] = getid3_lib::RGADadjustmentLookup($parsedFrame['raw']['track']['adjustment'], $parsedFrame['raw']['track']['signbit']); $parsedFrame['album']['name'] = getid3_lib::RGADnameLookup($parsedFrame['raw']['album']['name']); $parsedFrame['album']['originator'] = getid3_lib::RGADoriginatorLookup($parsedFrame['raw']['album']['originator']); $parsedFrame['album']['adjustment'] = getid3_lib::RGADadjustmentLookup($parsedFrame['raw']['album']['adjustment'], $parsedFrame['raw']['album']['signbit']); $info['replay_gain']['track']['peak'] = $parsedFrame['peakamplitude']; $info['replay_gain']['track']['originator'] = $parsedFrame['track']['originator']; $info['replay_gain']['track']['adjustment'] = $parsedFrame['track']['adjustment']; $info['replay_gain']['album']['originator'] = $parsedFrame['album']['originator']; $info['replay_gain']['album']['adjustment'] = $parsedFrame['album']['adjustment']; unset($parsedFrame['data']); } elseif (($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'CHAP')) { // CHAP Chapters frame (ID3v2.3+ only) // http://id3.org/id3v2-chapters-1.0 // <ID3v2.3 or ID3v2.4 frame header, ID: "CHAP"> (10 bytes) // Element ID <text string> $00 // Start time $xx xx xx xx // End time $xx xx xx xx // Start offset $xx xx xx xx // End offset $xx xx xx xx // <Optional embedded sub-frames> $frame_offset = 0; @list($parsedFrame['element_id']) = explode("\x00", $parsedFrame['data'], 2); $frame_offset += strlen($parsedFrame['element_id']."\x00"); $parsedFrame['time_begin'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 4)); $frame_offset += 4; $parsedFrame['time_end'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 4)); $frame_offset += 4; if (substr($parsedFrame['data'], $frame_offset, 4) != "\xFF\xFF\xFF\xFF") { // "If these bytes are all set to 0xFF then the value should be ignored and the start time value should be utilized." $parsedFrame['offset_begin'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 4)); } $frame_offset += 4; if (substr($parsedFrame['data'], $frame_offset, 4) != "\xFF\xFF\xFF\xFF") { // "If these bytes are all set to 0xFF then the value should be ignored and the start time value should be utilized." $parsedFrame['offset_end'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 4)); } $frame_offset += 4; if ($frame_offset < strlen($parsedFrame['data'])) { $parsedFrame['subframes'] = array(); while ($frame_offset < strlen($parsedFrame['data'])) { // <Optional embedded sub-frames> $subframe = array(); $subframe['name'] = substr($parsedFrame['data'], $frame_offset, 4); $frame_offset += 4; $subframe['size'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 4)); $frame_offset += 4; $subframe['flags_raw'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 2)); $frame_offset += 2; if ($subframe['size'] > (strlen($parsedFrame['data']) - $frame_offset)) { $this->warning('CHAP subframe "'.$subframe['name'].'" at frame offset '.$frame_offset.' claims to be "'.$subframe['size'].'" bytes, which is more than the available data ('.(strlen($parsedFrame['data']) - $frame_offset).' bytes)'); break; } $subframe_rawdata = substr($parsedFrame['data'], $frame_offset, $subframe['size']); $frame_offset += $subframe['size']; $subframe['encodingid'] = ord(substr($subframe_rawdata, 0, 1)); $subframe['text'] = substr($subframe_rawdata, 1); $subframe['encoding'] = $this->TextEncodingNameLookup($subframe['encodingid']); $encoding_converted_text = trim(getid3_lib::iconv_fallback($subframe['encoding'], $info['encoding'], $subframe['text'])); switch (substr($encoding_converted_text, 0, 2)) { case "\xFF\xFE": case "\xFE\xFF": switch (strtoupper($info['id3v2']['encoding'])) { case 'ISO-8859-1': case 'UTF-8': $encoding_converted_text = substr($encoding_converted_text, 2); // remove unwanted byte-order-marks break; default: // ignore break; } break; default: // do not remove BOM break; } switch ($subframe['name']) { case 'TIT2': $parsedFrame['chapter_name'] = $encoding_converted_text; $parsedFrame['subframes'][] = $subframe; break; case 'TIT3': $parsedFrame['chapter_description'] = $encoding_converted_text; $parsedFrame['subframes'][] = $subframe; break; case 'WXXX': @list($subframe['chapter_url_description'], $subframe['chapter_url']) = explode("\x00", $encoding_converted_text, 2); $parsedFrame['chapter_url'][$subframe['chapter_url_description']] = $subframe['chapter_url']; $parsedFrame['subframes'][] = $subframe; break; case 'APIC': if (preg_match('#^([^\\x00]+)*\\x00(.)([^\\x00]+)*\\x00(.+)$#s', $subframe['text'], $matches)) { list($dummy, $subframe_apic_mime, $subframe_apic_picturetype, $subframe_apic_description, $subframe_apic_picturedata) = $matches; $subframe['image_mime'] = trim(getid3_lib::iconv_fallback($subframe['encoding'], $info['encoding'], $subframe_apic_mime)); $subframe['picture_type'] = $this->APICPictureTypeLookup($subframe_apic_picturetype); $subframe['description'] = trim(getid3_lib::iconv_fallback($subframe['encoding'], $info['encoding'], $subframe_apic_description)); if (strlen($this->TextEncodingTerminatorLookup($subframe['encoding'])) == 2) { // the null terminator between "description" and "picture data" could be either 1 byte (ISO-8859-1, UTF-8) or two bytes (UTF-16) // the above regex assumes one byte, if it's actually two then strip the second one here $subframe_apic_picturedata = substr($subframe_apic_picturedata, 1); } $subframe['data'] = $subframe_apic_picturedata; unset($dummy, $subframe_apic_mime, $subframe_apic_picturetype, $subframe_apic_description, $subframe_apic_picturedata); unset($subframe['text'], $parsedFrame['text']); $parsedFrame['subframes'][] = $subframe; $parsedFrame['picture_present'] = true; } else { $this->warning('ID3v2.CHAP subframe #'.(count($parsedFrame['subframes']) + 1).' "'.$subframe['name'].'" not in expected format'); } break; default: $this->warning('ID3v2.CHAP subframe "'.$subframe['name'].'" not handled (supported: TIT2, TIT3, WXXX, APIC)'); break; } } unset($subframe_rawdata, $subframe, $encoding_converted_text); unset($parsedFrame['data']); // debatable whether this this be here, without it the returned structure may contain a large amount of duplicate data if chapters contain APIC } $id3v2_chapter_entry = array(); foreach (array('id', 'time_begin', 'time_end', 'offset_begin', 'offset_end', 'chapter_name', 'chapter_description', 'chapter_url', 'picture_present') as $id3v2_chapter_key) { if (isset($parsedFrame[$id3v2_chapter_key])) { $id3v2_chapter_entry[$id3v2_chapter_key] = $parsedFrame[$id3v2_chapter_key]; } } if (!isset($info['id3v2']['chapters'])) { $info['id3v2']['chapters'] = array(); } $info['id3v2']['chapters'][] = $id3v2_chapter_entry; unset($id3v2_chapter_entry, $id3v2_chapter_key); } elseif (($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'CTOC')) { // CTOC Chapters Table Of Contents frame (ID3v2.3+ only) // http://id3.org/id3v2-chapters-1.0 // <ID3v2.3 or ID3v2.4 frame header, ID: "CTOC"> (10 bytes) // Element ID <text string> $00 // CTOC flags %xx // Entry count $xx // Child Element ID <string>$00 /* zero or more child CHAP or CTOC entries */ // <Optional embedded sub-frames> $frame_offset = 0; @list($parsedFrame['element_id']) = explode("\x00", $parsedFrame['data'], 2); $frame_offset += strlen($parsedFrame['element_id']."\x00"); $ctoc_flags_raw = ord(substr($parsedFrame['data'], $frame_offset, 1)); $frame_offset += 1; $parsedFrame['entry_count'] = ord(substr($parsedFrame['data'], $frame_offset, 1)); $frame_offset += 1; $terminator_position = null; for ($i = 0; $i < $parsedFrame['entry_count']; $i++) { $terminator_position = strpos($parsedFrame['data'], "\x00", $frame_offset); $parsedFrame['child_element_ids'][$i] = substr($parsedFrame['data'], $frame_offset, $terminator_position - $frame_offset); $frame_offset = $terminator_position + 1; } $parsedFrame['ctoc_flags']['ordered'] = (bool) ($ctoc_flags_raw & 0x01); $parsedFrame['ctoc_flags']['top_level'] = (bool) ($ctoc_flags_raw & 0x03); unset($ctoc_flags_raw, $terminator_position); if ($frame_offset < strlen($parsedFrame['data'])) { $parsedFrame['subframes'] = array(); while ($frame_offset < strlen($parsedFrame['data'])) { // <Optional embedded sub-frames> $subframe = array(); $subframe['name'] = substr($parsedFrame['data'], $frame_offset, 4); $frame_offset += 4; $subframe['size'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 4)); $frame_offset += 4; $subframe['flags_raw'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 2)); $frame_offset += 2; if ($subframe['size'] > (strlen($parsedFrame['data']) - $frame_offset)) { $this->warning('CTOS subframe "'.$subframe['name'].'" at frame offset '.$frame_offset.' claims to be "'.$subframe['size'].'" bytes, which is more than the available data ('.(strlen($parsedFrame['data']) - $frame_offset).' bytes)'); break; } $subframe_rawdata = substr($parsedFrame['data'], $frame_offset, $subframe['size']); $frame_offset += $subframe['size']; $subframe['encodingid'] = ord(substr($subframe_rawdata, 0, 1)); $subframe['text'] = substr($subframe_rawdata, 1); $subframe['encoding'] = $this->TextEncodingNameLookup($subframe['encodingid']); $encoding_converted_text = trim(getid3_lib::iconv_fallback($subframe['encoding'], $info['encoding'], $subframe['text']));; switch (substr($encoding_converted_text, 0, 2)) { case "\xFF\xFE": case "\xFE\xFF": switch (strtoupper($info['id3v2']['encoding'])) { case 'ISO-8859-1': case 'UTF-8': $encoding_converted_text = substr($encoding_converted_text, 2); // remove unwanted byte-order-marks break; default: // ignore break; } break; default: // do not remove BOM break; } if (($subframe['name'] == 'TIT2') || ($subframe['name'] == 'TIT3')) { if ($subframe['name'] == 'TIT2') { $parsedFrame['toc_name'] = $encoding_converted_text; } elseif ($subframe['name'] == 'TIT3') { $parsedFrame['toc_description'] = $encoding_converted_text; } $parsedFrame['subframes'][] = $subframe; } else { $this->warning('ID3v2.CTOC subframe "'.$subframe['name'].'" not handled (only TIT2 and TIT3)'); } } unset($subframe_rawdata, $subframe, $encoding_converted_text); } } return true; } /** * @param string $data * * @return string */ public function DeUnsynchronise($data) { return str_replace("\xFF\x00", "\xFF", $data); } /** * @param int $index * * @return string */ public function LookupExtendedHeaderRestrictionsTagSizeLimits($index) { static $LookupExtendedHeaderRestrictionsTagSizeLimits = array( 0x00 => 'No more than 128 frames and 1 MB total tag size', 0x01 => 'No more than 64 frames and 128 KB total tag size', 0x02 => 'No more than 32 frames and 40 KB total tag size', 0x03 => 'No more than 32 frames and 4 KB total tag size', ); return (isset($LookupExtendedHeaderRestrictionsTagSizeLimits[$index]) ? $LookupExtendedHeaderRestrictionsTagSizeLimits[$index] : ''); } /** * @param int $index * * @return string */ public function LookupExtendedHeaderRestrictionsTextEncodings($index) { static $LookupExtendedHeaderRestrictionsTextEncodings = array( 0x00 => 'No restrictions', 0x01 => 'Strings are only encoded with ISO-8859-1 or UTF-8', ); return (isset($LookupExtendedHeaderRestrictionsTextEncodings[$index]) ? $LookupExtendedHeaderRestrictionsTextEncodings[$index] : ''); } /** * @param int $index * * @return string */ public function LookupExtendedHeaderRestrictionsTextFieldSize($index) { static $LookupExtendedHeaderRestrictionsTextFieldSize = array( 0x00 => 'No restrictions', 0x01 => 'No string is longer than 1024 characters', 0x02 => 'No string is longer than 128 characters', 0x03 => 'No string is longer than 30 characters', ); return (isset($LookupExtendedHeaderRestrictionsTextFieldSize[$index]) ? $LookupExtendedHeaderRestrictionsTextFieldSize[$index] : ''); } /** * @param int $index * * @return string */ public function LookupExtendedHeaderRestrictionsImageEncoding($index) { static $LookupExtendedHeaderRestrictionsImageEncoding = array( 0x00 => 'No restrictions', 0x01 => 'Images are encoded only with PNG or JPEG', ); return (isset($LookupExtendedHeaderRestrictionsImageEncoding[$index]) ? $LookupExtendedHeaderRestrictionsImageEncoding[$index] : ''); } /** * @param int $index * * @return string */ public function LookupExtendedHeaderRestrictionsImageSizeSize($index) { static $LookupExtendedHeaderRestrictionsImageSizeSize = array( 0x00 => 'No restrictions', 0x01 => 'All images are 256x256 pixels or smaller', 0x02 => 'All images are 64x64 pixels or smaller', 0x03 => 'All images are exactly 64x64 pixels, unless required otherwise', ); return (isset($LookupExtendedHeaderRestrictionsImageSizeSize[$index]) ? $LookupExtendedHeaderRestrictionsImageSizeSize[$index] : ''); } /** * @param string $currencyid * * @return string */ public function LookupCurrencyUnits($currencyid) { $begin = __LINE__; /** This is not a comment! AED Dirhams AFA Afghanis ALL Leke AMD Drams ANG Guilders AOA Kwanza ARS Pesos ATS Schillings AUD Dollars AWG Guilders AZM Manats BAM Convertible Marka BBD Dollars BDT Taka BEF Francs BGL Leva BHD Dinars BIF Francs BMD Dollars BND Dollars BOB Bolivianos BRL Brazil Real BSD Dollars BTN Ngultrum BWP Pulas BYR Rubles BZD Dollars CAD Dollars CDF Congolese Francs CHF Francs CLP Pesos CNY Yuan Renminbi COP Pesos CRC Colones CUP Pesos CVE Escudos CYP Pounds CZK Koruny DEM Deutsche Marks DJF Francs DKK Kroner DOP Pesos DZD Algeria Dinars EEK Krooni EGP Pounds ERN Nakfa ESP Pesetas ETB Birr EUR Euro FIM Markkaa FJD Dollars FKP Pounds FRF Francs GBP Pounds GEL Lari GGP Pounds GHC Cedis GIP Pounds GMD Dalasi GNF Francs GRD Drachmae GTQ Quetzales GYD Dollars HKD Dollars HNL Lempiras HRK Kuna HTG Gourdes HUF Forints IDR Rupiahs IEP Pounds ILS New Shekels IMP Pounds INR Rupees IQD Dinars IRR Rials ISK Kronur ITL Lire JEP Pounds JMD Dollars JOD Dinars JPY Yen KES Shillings KGS Soms KHR Riels KMF Francs KPW Won KWD Dinars KYD Dollars KZT Tenge LAK Kips LBP Pounds LKR Rupees LRD Dollars LSL Maloti LTL Litai LUF Francs LVL Lati LYD Dinars MAD Dirhams MDL Lei MGF Malagasy Francs MKD Denars MMK Kyats MNT Tugriks MOP Patacas MRO Ouguiyas MTL Liri MUR Rupees MVR Rufiyaa MWK Kwachas MXN Pesos MYR Ringgits MZM Meticais NAD Dollars NGN Nairas NIO Gold Cordobas NLG Guilders NOK Krone NPR Nepal Rupees NZD Dollars OMR Rials PAB Balboa PEN Nuevos Soles PGK Kina PHP Pesos PKR Rupees PLN Zlotych PTE Escudos PYG Guarani QAR Rials ROL Lei RUR Rubles RWF Rwanda Francs SAR Riyals SBD Dollars SCR Rupees SDD Dinars SEK Kronor SGD Dollars SHP Pounds SIT Tolars SKK Koruny SLL Leones SOS Shillings SPL Luigini SRG Guilders STD Dobras SVC Colones SYP Pounds SZL Emalangeni THB Baht TJR Rubles TMM Manats TND Dinars TOP Pa'anga TRL Liras (old) TRY Liras TTD Dollars TVD Tuvalu Dollars TWD New Dollars TZS Shillings UAH Hryvnia UGX Shillings USD Dollars UYU Pesos UZS Sums VAL Lire VEB Bolivares VND Dong VUV Vatu WST Tala XAF Francs XAG Ounces XAU Ounces XCD Dollars XDR Special Drawing Rights XPD Ounces XPF Francs XPT Ounces YER Rials YUM New Dinars ZAR Rand ZMK Kwacha ZWD Zimbabwe Dollars */ return getid3_lib::EmbeddedLookup($currencyid, $begin, __LINE__, __FILE__, 'id3v2-currency-units'); } /** * @param string $currencyid * * @return string */ public function LookupCurrencyCountry($currencyid) { $begin = __LINE__; /** This is not a comment! AED United Arab Emirates AFA Afghanistan ALL Albania AMD Armenia ANG Netherlands Antilles AOA Angola ARS Argentina ATS Austria AUD Australia AWG Aruba AZM Azerbaijan BAM Bosnia and Herzegovina BBD Barbados BDT Bangladesh BEF Belgium BGL Bulgaria BHD Bahrain BIF Burundi BMD Bermuda BND Brunei Darussalam BOB Bolivia BRL Brazil BSD Bahamas BTN Bhutan BWP Botswana BYR Belarus BZD Belize CAD Canada CDF Congo/Kinshasa CHF Switzerland CLP Chile CNY China COP Colombia CRC Costa Rica CUP Cuba CVE Cape Verde CYP Cyprus CZK Czech Republic DEM Germany DJF Djibouti DKK Denmark DOP Dominican Republic DZD Algeria EEK Estonia EGP Egypt ERN Eritrea ESP Spain ETB Ethiopia EUR Euro Member Countries FIM Finland FJD Fiji FKP Falkland Islands (Malvinas) FRF France GBP United Kingdom GEL Georgia GGP Guernsey GHC Ghana GIP Gibraltar GMD Gambia GNF Guinea GRD Greece GTQ Guatemala GYD Guyana HKD Hong Kong HNL Honduras HRK Croatia HTG Haiti HUF Hungary IDR Indonesia IEP Ireland (Eire) ILS Israel IMP Isle of Man INR India IQD Iraq IRR Iran ISK Iceland ITL Italy JEP Jersey JMD Jamaica JOD Jordan JPY Japan KES Kenya KGS Kyrgyzstan KHR Cambodia KMF Comoros KPW Korea KWD Kuwait KYD Cayman Islands KZT Kazakstan LAK Laos LBP Lebanon LKR Sri Lanka LRD Liberia LSL Lesotho LTL Lithuania LUF Luxembourg LVL Latvia LYD Libya MAD Morocco MDL Moldova MGF Madagascar MKD Macedonia MMK Myanmar (Burma) MNT Mongolia MOP Macau MRO Mauritania MTL Malta MUR Mauritius MVR Maldives (Maldive Islands) MWK Malawi MXN Mexico MYR Malaysia MZM Mozambique NAD Namibia NGN Nigeria NIO Nicaragua NLG Netherlands (Holland) NOK Norway NPR Nepal NZD New Zealand OMR Oman PAB Panama PEN Peru PGK Papua New Guinea PHP Philippines PKR Pakistan PLN Poland PTE Portugal PYG Paraguay QAR Qatar ROL Romania RUR Russia RWF Rwanda SAR Saudi Arabia SBD Solomon Islands SCR Seychelles SDD Sudan SEK Sweden SGD Singapore SHP Saint Helena SIT Slovenia SKK Slovakia SLL Sierra Leone SOS Somalia SPL Seborga SRG Suriname STD São Tome and Principe SVC El Salvador SYP Syria SZL Swaziland THB Thailand TJR Tajikistan TMM Turkmenistan TND Tunisia TOP Tonga TRL Turkey TRY Turkey TTD Trinidad and Tobago TVD Tuvalu TWD Taiwan TZS Tanzania UAH Ukraine UGX Uganda USD United States of America UYU Uruguay UZS Uzbekistan VAL Vatican City VEB Venezuela VND Viet Nam VUV Vanuatu WST Samoa XAF Communauté Financière Africaine XAG Silver XAU Gold XCD East Caribbean XDR International Monetary Fund XPD Palladium XPF Comptoirs Français du Pacifique XPT Platinum YER Yemen YUM Yugoslavia ZAR South Africa ZMK Zambia ZWD Zimbabwe */ return getid3_lib::EmbeddedLookup($currencyid, $begin, __LINE__, __FILE__, 'id3v2-currency-country'); } /** * @param string $languagecode * @param bool $casesensitive * * @return string */ public static function LanguageLookup($languagecode, $casesensitive=false) { if (!$casesensitive) { $languagecode = strtolower($languagecode); } // http://www.id3.org/id3v2.4.0-structure.txt // [4. ID3v2 frame overview] // The three byte language field, present in several frames, is used to // describe the language of the frame's content, according to ISO-639-2 // [ISO-639-2]. The language should be represented in lower case. If the // language is not known the string "XXX" should be used. // ISO 639-2 - http://www.id3.org/iso639-2.html $begin = __LINE__; /** This is not a comment! XXX unknown xxx unknown aar Afar abk Abkhazian ace Achinese ach Acoli ada Adangme afa Afro-Asiatic (Other) afh Afrihili afr Afrikaans aka Akan akk Akkadian alb Albanian ale Aleut alg Algonquian Languages amh Amharic ang English, Old (ca. 450-1100) apa Apache Languages ara Arabic arc Aramaic arm Armenian arn Araucanian arp Arapaho art Artificial (Other) arw Arawak asm Assamese ath Athapascan Languages ava Avaric ave Avestan awa Awadhi aym Aymara aze Azerbaijani bad Banda bai Bamileke Languages bak Bashkir bal Baluchi bam Bambara ban Balinese baq Basque bas Basa bat Baltic (Other) bej Beja bel Byelorussian bem Bemba ben Bengali ber Berber (Other) bho Bhojpuri bih Bihari bik Bikol bin Bini bis Bislama bla Siksika bnt Bantu (Other) bod Tibetan bra Braj bre Breton bua Buriat bug Buginese bul Bulgarian bur Burmese cad Caddo cai Central American Indian (Other) car Carib cat Catalan cau Caucasian (Other) ceb Cebuano cel Celtic (Other) ces Czech cha Chamorro chb Chibcha che Chechen chg Chagatai chi Chinese chm Mari chn Chinook jargon cho Choctaw chr Cherokee chu Church Slavic chv Chuvash chy Cheyenne cop Coptic cor Cornish cos Corsican cpe Creoles and Pidgins, English-based (Other) cpf Creoles and Pidgins, French-based (Other) cpp Creoles and Pidgins, Portuguese-based (Other) cre Cree crp Creoles and Pidgins (Other) cus Cushitic (Other) cym Welsh cze Czech dak Dakota dan Danish del Delaware deu German din Dinka div Divehi doi Dogri dra Dravidian (Other) dua Duala dum Dutch, Middle (ca. 1050-1350) dut Dutch dyu Dyula dzo Dzongkha efi Efik egy Egyptian (Ancient) eka Ekajuk ell Greek, Modern (1453-) elx Elamite eng English enm English, Middle (ca. 1100-1500) epo Esperanto esk Eskimo (Other) esl Spanish est Estonian eus Basque ewe Ewe ewo Ewondo fan Fang fao Faroese fas Persian fat Fanti fij Fijian fin Finnish fiu Finno-Ugrian (Other) fon Fon fra French fre French frm French, Middle (ca. 1400-1600) fro French, Old (842- ca. 1400) fry Frisian ful Fulah gaa Ga gae Gaelic (Scots) gai Irish gay Gayo gdh Gaelic (Scots) gem Germanic (Other) geo Georgian ger German gez Geez gil Gilbertese glg Gallegan gmh German, Middle High (ca. 1050-1500) goh German, Old High (ca. 750-1050) gon Gondi got Gothic grb Grebo grc Greek, Ancient (to 1453) gre Greek, Modern (1453-) grn Guarani guj Gujarati hai Haida hau Hausa haw Hawaiian heb Hebrew her Herero hil Hiligaynon him Himachali hin Hindi hmo Hiri Motu hun Hungarian hup Hupa hye Armenian iba Iban ibo Igbo ice Icelandic ijo Ijo iku Inuktitut ilo Iloko ina Interlingua (International Auxiliary language Association) inc Indic (Other) ind Indonesian ine Indo-European (Other) ine Interlingue ipk Inupiak ira Iranian (Other) iri Irish iro Iroquoian uages isl Icelandic ita Italian jav Javanese jaw Javanese jpn Japanese jpr Judeo-Persian jrb Judeo-Arabic kaa Kara-Kalpak kab Kabyle kac Kachin kal Greenlandic kam Kamba kan Kannada kar Karen kas Kashmiri kat Georgian kau Kanuri kaw Kawi kaz Kazakh kha Khasi khi Khoisan (Other) khm Khmer kho Khotanese kik Kikuyu kin Kinyarwanda kir Kirghiz kok Konkani kom Komi kon Kongo kor Korean kpe Kpelle kro Kru kru Kurukh kua Kuanyama kum Kumyk kur Kurdish kus Kusaie kut Kutenai lad Ladino lah Lahnda lam Lamba lao Lao lat Latin lav Latvian lez Lezghian lin Lingala lit Lithuanian lol Mongo loz Lozi ltz Letzeburgesch lub Luba-Katanga lug Ganda lui Luiseno lun Lunda luo Luo (Kenya and Tanzania) mac Macedonian mad Madurese mag Magahi mah Marshall mai Maithili mak Macedonian mak Makasar mal Malayalam man Mandingo mao Maori map Austronesian (Other) mar Marathi mas Masai max Manx may Malay men Mende mga Irish, Middle (900 - 1200) mic Micmac min Minangkabau mis Miscellaneous (Other) mkh Mon-Kmer (Other) mlg Malagasy mlt Maltese mni Manipuri mno Manobo Languages moh Mohawk mol Moldavian mon Mongolian mos Mossi mri Maori msa Malay mul Multiple Languages mun Munda Languages mus Creek mwr Marwari mya Burmese myn Mayan Languages nah Aztec nai North American Indian (Other) nau Nauru nav Navajo nbl Ndebele, South nde Ndebele, North ndo Ndongo nep Nepali new Newari nic Niger-Kordofanian (Other) niu Niuean nla Dutch nno Norwegian (Nynorsk) non Norse, Old nor Norwegian nso Sotho, Northern nub Nubian Languages nya Nyanja nym Nyamwezi nyn Nyankole nyo Nyoro nzi Nzima oci Langue d'Oc (post 1500) oji Ojibwa ori Oriya orm Oromo osa Osage oss Ossetic ota Turkish, Ottoman (1500 - 1928) oto Otomian Languages paa Papuan-Australian (Other) pag Pangasinan pal Pahlavi pam Pampanga pan Panjabi pap Papiamento pau Palauan peo Persian, Old (ca 600 - 400 B.C.) per Persian phn Phoenician pli Pali pol Polish pon Ponape por Portuguese pra Prakrit uages pro Provencal, Old (to 1500) pus Pushto que Quechua raj Rajasthani rar Rarotongan roa Romance (Other) roh Rhaeto-Romance rom Romany ron Romanian rum Romanian run Rundi rus Russian sad Sandawe sag Sango sah Yakut sai South American Indian (Other) sal Salishan Languages sam Samaritan Aramaic san Sanskrit sco Scots scr Serbo-Croatian sel Selkup sem Semitic (Other) sga Irish, Old (to 900) shn Shan sid Sidamo sin Singhalese sio Siouan Languages sit Sino-Tibetan (Other) sla Slavic (Other) slk Slovak slo Slovak slv Slovenian smi Sami Languages smo Samoan sna Shona snd Sindhi sog Sogdian som Somali son Songhai sot Sotho, Southern spa Spanish sqi Albanian srd Sardinian srr Serer ssa Nilo-Saharan (Other) ssw Siswant ssw Swazi suk Sukuma sun Sudanese sus Susu sux Sumerian sve Swedish swa Swahili swe Swedish syr Syriac tah Tahitian tam Tamil tat Tatar tel Telugu tem Timne ter Tereno tgk Tajik tgl Tagalog tha Thai tib Tibetan tig Tigre tir Tigrinya tiv Tivi tli Tlingit tmh Tamashek tog Tonga (Nyasa) ton Tonga (Tonga Islands) tru Truk tsi Tsimshian tsn Tswana tso Tsonga tuk Turkmen tum Tumbuka tur Turkish tut Altaic (Other) twi Twi tyv Tuvinian uga Ugaritic uig Uighur ukr Ukrainian umb Umbundu und Undetermined urd Urdu uzb Uzbek vai Vai ven Venda vie Vietnamese vol Volapük vot Votic wak Wakashan Languages wal Walamo war Waray was Washo wel Welsh wen Sorbian Languages wol Wolof xho Xhosa yao Yao yap Yap yid Yiddish yor Yoruba zap Zapotec zen Zenaga zha Zhuang zho Chinese zul Zulu zun Zuni */ return getid3_lib::EmbeddedLookup($languagecode, $begin, __LINE__, __FILE__, 'id3v2-languagecode'); } /** * @param int $index * * @return string */ public static function ETCOEventLookup($index) { if (($index >= 0x17) && ($index <= 0xDF)) { return 'reserved for future use'; } if (($index >= 0xE0) && ($index <= 0xEF)) { return 'not predefined synch 0-F'; } if (($index >= 0xF0) && ($index <= 0xFC)) { return 'reserved for future use'; } static $EventLookup = array( 0x00 => 'padding (has no meaning)', 0x01 => 'end of initial silence', 0x02 => 'intro start', 0x03 => 'main part start', 0x04 => 'outro start', 0x05 => 'outro end', 0x06 => 'verse start', 0x07 => 'refrain start', 0x08 => 'interlude start', 0x09 => 'theme start', 0x0A => 'variation start', 0x0B => 'key change', 0x0C => 'time change', 0x0D => 'momentary unwanted noise (Snap, Crackle & Pop)', 0x0E => 'sustained noise', 0x0F => 'sustained noise end', 0x10 => 'intro end', 0x11 => 'main part end', 0x12 => 'verse end', 0x13 => 'refrain end', 0x14 => 'theme end', 0x15 => 'profanity', 0x16 => 'profanity end', 0xFD => 'audio end (start of silence)', 0xFE => 'audio file ends', 0xFF => 'one more byte of events follows' ); return (isset($EventLookup[$index]) ? $EventLookup[$index] : ''); } /** * @param int $index * * @return string */ public static function SYTLContentTypeLookup($index) { static $SYTLContentTypeLookup = array( 0x00 => 'other', 0x01 => 'lyrics', 0x02 => 'text transcription', 0x03 => 'movement/part name', // (e.g. 'Adagio') 0x04 => 'events', // (e.g. 'Don Quijote enters the stage') 0x05 => 'chord', // (e.g. 'Bb F Fsus') 0x06 => 'trivia/\'pop up\' information', 0x07 => 'URLs to webpages', 0x08 => 'URLs to images' ); return (isset($SYTLContentTypeLookup[$index]) ? $SYTLContentTypeLookup[$index] : ''); } /** * @param int $index * @param bool $returnarray * * @return array|string */ public static function APICPictureTypeLookup($index, $returnarray=false) { static $APICPictureTypeLookup = array( 0x00 => 'Other', 0x01 => '32x32 pixels \'file icon\' (PNG only)', 0x02 => 'Other file icon', 0x03 => 'Cover (front)', 0x04 => 'Cover (back)', 0x05 => 'Leaflet page', 0x06 => 'Media (e.g. label side of CD)', 0x07 => 'Lead artist/lead performer/soloist', 0x08 => 'Artist/performer', 0x09 => 'Conductor', 0x0A => 'Band/Orchestra', 0x0B => 'Composer', 0x0C => 'Lyricist/text writer', 0x0D => 'Recording Location', 0x0E => 'During recording', 0x0F => 'During performance', 0x10 => 'Movie/video screen capture', 0x11 => 'A bright coloured fish', 0x12 => 'Illustration', 0x13 => 'Band/artist logotype', 0x14 => 'Publisher/Studio logotype' ); if ($returnarray) { return $APICPictureTypeLookup; } return (isset($APICPictureTypeLookup[$index]) ? $APICPictureTypeLookup[$index] : ''); } /** * @param int $index * * @return string */ public static function COMRReceivedAsLookup($index) { static $COMRReceivedAsLookup = array( 0x00 => 'Other', 0x01 => 'Standard CD album with other songs', 0x02 => 'Compressed audio on CD', 0x03 => 'File over the Internet', 0x04 => 'Stream over the Internet', 0x05 => 'As note sheets', 0x06 => 'As note sheets in a book with other sheets', 0x07 => 'Music on other media', 0x08 => 'Non-musical merchandise' ); return (isset($COMRReceivedAsLookup[$index]) ? $COMRReceivedAsLookup[$index] : ''); } /** * @param int $index * * @return string */ public static function RVA2ChannelTypeLookup($index) { static $RVA2ChannelTypeLookup = array( 0x00 => 'Other', 0x01 => 'Master volume', 0x02 => 'Front right', 0x03 => 'Front left', 0x04 => 'Back right', 0x05 => 'Back left', 0x06 => 'Front centre', 0x07 => 'Back centre', 0x08 => 'Subwoofer' ); return (isset($RVA2ChannelTypeLookup[$index]) ? $RVA2ChannelTypeLookup[$index] : ''); } /** * @param string $framename * * @return string */ public static function FrameNameLongLookup($framename) { $begin = __LINE__; /** This is not a comment! AENC Audio encryption APIC Attached picture ASPI Audio seek point index BUF Recommended buffer size CNT Play counter COM Comments COMM Comments COMR Commercial frame CRA Audio encryption CRM Encrypted meta frame ENCR Encryption method registration EQU Equalisation EQU2 Equalisation (2) EQUA Equalisation ETC Event timing codes ETCO Event timing codes GEO General encapsulated object GEOB General encapsulated object GRID Group identification registration IPL Involved people list IPLS Involved people list LINK Linked information LNK Linked information MCDI Music CD identifier MCI Music CD Identifier MLL MPEG location lookup table MLLT MPEG location lookup table OWNE Ownership frame PCNT Play counter PIC Attached picture POP Popularimeter POPM Popularimeter POSS Position synchronisation frame PRIV Private frame RBUF Recommended buffer size REV Reverb RVA Relative volume adjustment RVA2 Relative volume adjustment (2) RVAD Relative volume adjustment RVRB Reverb SEEK Seek frame SIGN Signature frame SLT Synchronised lyric/text STC Synced tempo codes SYLT Synchronised lyric/text SYTC Synchronised tempo codes TAL Album/Movie/Show title TALB Album/Movie/Show title TBP BPM (Beats Per Minute) TBPM BPM (beats per minute) TCM Composer TCMP Part of a compilation TCO Content type TCOM Composer TCON Content type TCOP Copyright message TCP Part of a compilation TCR Copyright message TDA Date TDAT Date TDEN Encoding time TDLY Playlist delay TDOR Original release time TDRC Recording time TDRL Release time TDTG Tagging time TDY Playlist delay TEN Encoded by TENC Encoded by TEXT Lyricist/Text writer TFLT File type TFT File type TIM Time TIME Time TIPL Involved people list TIT1 Content group description TIT2 Title/songname/content description TIT3 Subtitle/Description refinement TKE Initial key TKEY Initial key TLA Language(s) TLAN Language(s) TLE Length TLEN Length TMCL Musician credits list TMED Media type TMOO Mood TMT Media type TOA Original artist(s)/performer(s) TOAL Original album/movie/show title TOF Original filename TOFN Original filename TOL Original Lyricist(s)/text writer(s) TOLY Original lyricist(s)/text writer(s) TOPE Original artist(s)/performer(s) TOR Original release year TORY Original release year TOT Original album/Movie/Show title TOWN File owner/licensee TP1 Lead artist(s)/Lead performer(s)/Soloist(s)/Performing group TP2 Band/Orchestra/Accompaniment TP3 Conductor/Performer refinement TP4 Interpreted, remixed, or otherwise modified by TPA Part of a set TPB Publisher TPE1 Lead performer(s)/Soloist(s) TPE2 Band/orchestra/accompaniment TPE3 Conductor/performer refinement TPE4 Interpreted, remixed, or otherwise modified by TPOS Part of a set TPRO Produced notice TPUB Publisher TRC ISRC (International Standard Recording Code) TRCK Track number/Position in set TRD Recording dates TRDA Recording dates TRK Track number/Position in set TRSN Internet radio station name TRSO Internet radio station owner TS2 Album-Artist sort order TSA Album sort order TSC Composer sort order TSI Size TSIZ Size TSO2 Album-Artist sort order TSOA Album sort order TSOC Composer sort order TSOP Performer sort order TSOT Title sort order TSP Performer sort order TSRC ISRC (international standard recording code) TSS Software/hardware and settings used for encoding TSSE Software/Hardware and settings used for encoding TSST Set subtitle TST Title sort order TT1 Content group description TT2 Title/Songname/Content description TT3 Subtitle/Description refinement TXT Lyricist/text writer TXX User defined text information frame TXXX User defined text information frame TYE Year TYER Year UFI Unique file identifier UFID Unique file identifier ULT Unsynchronised lyric/text transcription USER Terms of use USLT Unsynchronised lyric/text transcription WAF Official audio file webpage WAR Official artist/performer webpage WAS Official audio source webpage WCM Commercial information WCOM Commercial information WCOP Copyright/Legal information WCP Copyright/Legal information WOAF Official audio file webpage WOAR Official artist/performer webpage WOAS Official audio source webpage WORS Official Internet radio station homepage WPAY Payment WPB Publishers official webpage WPUB Publishers official webpage WXX User defined URL link frame WXXX User defined URL link frame TFEA Featured Artist TSTU Recording Studio rgad Replay Gain Adjustment */ return getid3_lib::EmbeddedLookup($framename, $begin, __LINE__, __FILE__, 'id3v2-framename_long'); // Last three: // from Helium2 [www.helium2.com] // from http://privatewww.essex.ac.uk/~djmrob/replaygain/file_format_id3v2.html } /** * @param string $framename * * @return string */ public static function FrameNameShortLookup($framename) { $begin = __LINE__; /** This is not a comment! AENC audio_encryption APIC attached_picture ASPI audio_seek_point_index BUF recommended_buffer_size CNT play_counter COM comment COMM comment COMR commercial_frame CRA audio_encryption CRM encrypted_meta_frame ENCR encryption_method_registration EQU equalisation EQU2 equalisation EQUA equalisation ETC event_timing_codes ETCO event_timing_codes GEO general_encapsulated_object GEOB general_encapsulated_object GRID group_identification_registration IPL involved_people_list IPLS involved_people_list LINK linked_information LNK linked_information MCDI music_cd_identifier MCI music_cd_identifier MLL mpeg_location_lookup_table MLLT mpeg_location_lookup_table OWNE ownership_frame PCNT play_counter PIC attached_picture POP popularimeter POPM popularimeter POSS position_synchronisation_frame PRIV private_frame RBUF recommended_buffer_size REV reverb RVA relative_volume_adjustment RVA2 relative_volume_adjustment RVAD relative_volume_adjustment RVRB reverb SEEK seek_frame SIGN signature_frame SLT synchronised_lyric STC synced_tempo_codes SYLT synchronised_lyric SYTC synchronised_tempo_codes TAL album TALB album TBP bpm TBPM bpm TCM composer TCMP part_of_a_compilation TCO genre TCOM composer TCON genre TCOP copyright_message TCP part_of_a_compilation TCR copyright_message TDA date TDAT date TDEN encoding_time TDLY playlist_delay TDOR original_release_time TDRC recording_time TDRL release_time TDTG tagging_time TDY playlist_delay TEN encoded_by TENC encoded_by TEXT lyricist TFLT file_type TFT file_type TIM time TIME time TIPL involved_people_list TIT1 content_group_description TIT2 title TIT3 subtitle TKE initial_key TKEY initial_key TLA language TLAN language TLE length TLEN length TMCL musician_credits_list TMED media_type TMOO mood TMT media_type TOA original_artist TOAL original_album TOF original_filename TOFN original_filename TOL original_lyricist TOLY original_lyricist TOPE original_artist TOR original_year TORY original_year TOT original_album TOWN file_owner TP1 artist TP2 band TP3 conductor TP4 remixer TPA part_of_a_set TPB publisher TPE1 artist TPE2 band TPE3 conductor TPE4 remixer TPOS part_of_a_set TPRO produced_notice TPUB publisher TRC isrc TRCK track_number TRD recording_dates TRDA recording_dates TRK track_number TRSN internet_radio_station_name TRSO internet_radio_station_owner TS2 album_artist_sort_order TSA album_sort_order TSC composer_sort_order TSI size TSIZ size TSO2 album_artist_sort_order TSOA album_sort_order TSOC composer_sort_order TSOP performer_sort_order TSOT title_sort_order TSP performer_sort_order TSRC isrc TSS encoder_settings TSSE encoder_settings TSST set_subtitle TST title_sort_order TT1 content_group_description TT2 title TT3 subtitle TXT lyricist TXX text TXXX text TYE year TYER year UFI unique_file_identifier UFID unique_file_identifier ULT unsynchronised_lyric USER terms_of_use USLT unsynchronised_lyric WAF url_file WAR url_artist WAS url_source WCM commercial_information WCOM commercial_information WCOP copyright WCP copyright WOAF url_file WOAR url_artist WOAS url_source WORS url_station WPAY url_payment WPB url_publisher WPUB url_publisher WXX url_user WXXX url_user TFEA featured_artist TSTU recording_studio rgad replay_gain_adjustment */ return getid3_lib::EmbeddedLookup($framename, $begin, __LINE__, __FILE__, 'id3v2-framename_short'); } /** * @param string $encoding * * @return string */ public static function TextEncodingTerminatorLookup($encoding) { // http://www.id3.org/id3v2.4.0-structure.txt // Frames that allow different types of text encoding contains a text encoding description byte. Possible encodings: static $TextEncodingTerminatorLookup = array( 0 => "\x00", // $00 ISO-8859-1. Terminated with $00. 1 => "\x00\x00", // $01 UTF-16 encoded Unicode with BOM. All strings in the same frame SHALL have the same byteorder. Terminated with $00 00. 2 => "\x00\x00", // $02 UTF-16BE encoded Unicode without BOM. Terminated with $00 00. 3 => "\x00", // $03 UTF-8 encoded Unicode. Terminated with $00. 255 => "\x00\x00" ); return (isset($TextEncodingTerminatorLookup[$encoding]) ? $TextEncodingTerminatorLookup[$encoding] : "\x00"); } /** * @param int $encoding * * @return string */ public static function TextEncodingNameLookup($encoding) { // http://www.id3.org/id3v2.4.0-structure.txt // Frames that allow different types of text encoding contains a text encoding description byte. Possible encodings: static $TextEncodingNameLookup = array( 0 => 'ISO-8859-1', // $00 ISO-8859-1. Terminated with $00. 1 => 'UTF-16', // $01 UTF-16 encoded Unicode with BOM. All strings in the same frame SHALL have the same byteorder. Terminated with $00 00. 2 => 'UTF-16BE', // $02 UTF-16BE encoded Unicode without BOM. Terminated with $00 00. 3 => 'UTF-8', // $03 UTF-8 encoded Unicode. Terminated with $00. 255 => 'UTF-16BE' ); return (isset($TextEncodingNameLookup[$encoding]) ? $TextEncodingNameLookup[$encoding] : 'ISO-8859-1'); } /** * @param string $string * @param string $terminator * * @return string */ public static function RemoveStringTerminator($string, $terminator) { // Null terminator at end of comment string is somewhat ambiguous in the specification, may or may not be implemented by various taggers. Remove terminator only if present. // https://github.com/JamesHeinrich/getID3/issues/121 // https://community.mp3tag.de/t/x-trailing-nulls-in-id3v2-comments/19227 if (substr($string, -strlen($terminator), strlen($terminator)) === $terminator) { $string = substr($string, 0, -strlen($terminator)); } return $string; } /** * @param string $string * * @return string */ public static function MakeUTF16emptyStringEmpty($string) { if (in_array($string, array("\x00", "\x00\x00", "\xFF\xFE", "\xFE\xFF"))) { // if string only contains a BOM or terminator then make it actually an empty string $string = ''; } return $string; } /** * @param string $framename * @param int $id3v2majorversion * * @return bool|int */ public static function IsValidID3v2FrameName($framename, $id3v2majorversion) { switch ($id3v2majorversion) { case 2: return preg_match('#[A-Z][A-Z0-9]{2}#', $framename); case 3: case 4: return preg_match('#[A-Z][A-Z0-9]{3}#', $framename); } return false; } /** * @param string $numberstring * @param bool $allowdecimal * @param bool $allownegative * * @return bool */ public static function IsANumber($numberstring, $allowdecimal=false, $allownegative=false) { $pattern = '#^'; $pattern .= ($allownegative ? '\\-?' : ''); $pattern .= '[0-9]+'; $pattern .= ($allowdecimal ? '(\\.[0-9]+)?' : ''); $pattern .= '$#'; return preg_match($pattern, $numberstring); } /** * @param string $datestamp * * @return bool */ public static function IsValidDateStampString($datestamp) { if (!preg_match('#^[12][0-9]{3}[01][0-9][0123][0-9]$#', $datestamp)) { return false; } $year = substr($datestamp, 0, 4); $month = substr($datestamp, 4, 2); $day = substr($datestamp, 6, 2); if (($year == 0) || ($month == 0) || ($day == 0)) { return false; } if ($month > 12) { return false; } if ($day > 31) { return false; } if (($day > 30) && (($month == 4) || ($month == 6) || ($month == 9) || ($month == 11))) { return false; } if (($day > 29) && ($month == 2)) { return false; } return true; } /** * @param int $majorversion * * @return int */ public static function ID3v2HeaderLength($majorversion) { return (($majorversion == 2) ? 6 : 10); } /** * @param string $frame_name * * @return string|false */ public static function ID3v22iTunesBrokenFrameName($frame_name) { // iTunes (multiple versions) has been known to write ID3v2.3 style frames // but use ID3v2.2 frame names, right-padded using either [space] or [null] // to make them fit in the 4-byte frame name space of the ID3v2.3 frame. // This function will detect and translate the corrupt frame name into ID3v2.3 standard. static $ID3v22_iTunes_BrokenFrames = array( 'BUF' => 'RBUF', // Recommended buffer size 'CNT' => 'PCNT', // Play counter 'COM' => 'COMM', // Comments 'CRA' => 'AENC', // Audio encryption 'EQU' => 'EQUA', // Equalisation 'ETC' => 'ETCO', // Event timing codes 'GEO' => 'GEOB', // General encapsulated object 'IPL' => 'IPLS', // Involved people list 'LNK' => 'LINK', // Linked information 'MCI' => 'MCDI', // Music CD identifier 'MLL' => 'MLLT', // MPEG location lookup table 'PIC' => 'APIC', // Attached picture 'POP' => 'POPM', // Popularimeter 'REV' => 'RVRB', // Reverb 'RVA' => 'RVAD', // Relative volume adjustment 'SLT' => 'SYLT', // Synchronised lyric/text 'STC' => 'SYTC', // Synchronised tempo codes 'TAL' => 'TALB', // Album/Movie/Show title 'TBP' => 'TBPM', // BPM (beats per minute) 'TCM' => 'TCOM', // Composer 'TCO' => 'TCON', // Content type 'TCP' => 'TCMP', // Part of a compilation 'TCR' => 'TCOP', // Copyright message 'TDA' => 'TDAT', // Date 'TDY' => 'TDLY', // Playlist delay 'TEN' => 'TENC', // Encoded by 'TFT' => 'TFLT', // File type 'TIM' => 'TIME', // Time 'TKE' => 'TKEY', // Initial key 'TLA' => 'TLAN', // Language(s) 'TLE' => 'TLEN', // Length 'TMT' => 'TMED', // Media type 'TOA' => 'TOPE', // Original artist(s)/performer(s) 'TOF' => 'TOFN', // Original filename 'TOL' => 'TOLY', // Original lyricist(s)/text writer(s) 'TOR' => 'TORY', // Original release year 'TOT' => 'TOAL', // Original album/movie/show title 'TP1' => 'TPE1', // Lead performer(s)/Soloist(s) 'TP2' => 'TPE2', // Band/orchestra/accompaniment 'TP3' => 'TPE3', // Conductor/performer refinement 'TP4' => 'TPE4', // Interpreted, remixed, or otherwise modified by 'TPA' => 'TPOS', // Part of a set 'TPB' => 'TPUB', // Publisher 'TRC' => 'TSRC', // ISRC (international standard recording code) 'TRD' => 'TRDA', // Recording dates 'TRK' => 'TRCK', // Track number/Position in set 'TS2' => 'TSO2', // Album-Artist sort order 'TSA' => 'TSOA', // Album sort order 'TSC' => 'TSOC', // Composer sort order 'TSI' => 'TSIZ', // Size 'TSP' => 'TSOP', // Performer sort order 'TSS' => 'TSSE', // Software/Hardware and settings used for encoding 'TST' => 'TSOT', // Title sort order 'TT1' => 'TIT1', // Content group description 'TT2' => 'TIT2', // Title/songname/content description 'TT3' => 'TIT3', // Subtitle/Description refinement 'TXT' => 'TEXT', // Lyricist/Text writer 'TXX' => 'TXXX', // User defined text information frame 'TYE' => 'TYER', // Year 'UFI' => 'UFID', // Unique file identifier 'ULT' => 'USLT', // Unsynchronised lyric/text transcription 'WAF' => 'WOAF', // Official audio file webpage 'WAR' => 'WOAR', // Official artist/performer webpage 'WAS' => 'WOAS', // Official audio source webpage 'WCM' => 'WCOM', // Commercial information 'WCP' => 'WCOP', // Copyright/Legal information 'WPB' => 'WPUB', // Publishers official webpage 'WXX' => 'WXXX', // User defined URL link frame ); if (strlen($frame_name) == 4) { if ((substr($frame_name, 3, 1) == ' ') || (substr($frame_name, 3, 1) == "\x00")) { if (isset($ID3v22_iTunes_BrokenFrames[substr($frame_name, 0, 3)])) { return $ID3v22_iTunes_BrokenFrames[substr($frame_name, 0, 3)]; } } } return false; } } module.audio.mp3.php 0000644 00000320627 15054343026 0010354 0 ustar 00 <?php ///////////////////////////////////////////////////////////////// /// 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']); } $CurrentDataLAMEversionString = null; if (((isset($info['id3v2']['headerlength']) && ($info['avdataoffset'] > $info['id3v2']['headerlength'])) || (!isset($info['id3v2']) && ($info['avdataoffset'] > 0) && ($info['avdataoffset'] != $initialOffset)))) { $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.'; } elseif (empty($info['id3v2']['headerlength']) && ($info['avdataoffset'] == $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.'; } } $this->warning($synchoffsetwarning); } if (isset($info['mpeg']['audio']['LAME'])) { $info['audio']['codec'] = 'LAME'; if (!empty($info['mpeg']['audio']['LAME']['long_version'])) { $info['audio']['encoder'] = rtrim($info['mpeg']['audio']['LAME']['long_version'], "\x00"); } elseif (!empty($info['mpeg']['audio']['LAME']['short_version'])) { $info['audio']['encoder'] = rtrim($info['mpeg']['audio']['LAME']['short_version'], "\x00"); } } $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; } $info['mime_type'] = 'audio/mpeg'; $info['audio']['lossless'] = 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); $info['playtime_seconds'] = ($info['avdataend'] - $info['avdataoffset'] - $xingVBRheaderFrameLength) * 8 / $info['audio']['bitrate']; } $info['audio']['encoder_options'] = $this->GuessEncoderOptions(); return true; } /** * @return string */ public function GuessEncoderOptions() { // shortcuts $info = &$this->getid3->info; $thisfile_mpeg_audio = array(); $thisfile_mpeg_audio_lame = array(); if (!empty($info['mpeg']['audio'])) { $thisfile_mpeg_audio = &$info['mpeg']['audio']; if (!empty($thisfile_mpeg_audio['LAME'])) { $thisfile_mpeg_audio_lame = &$thisfile_mpeg_audio['LAME']; } } $encoder_options = ''; static $NamedPresetBitrates = array(16, 24, 40, 56, 112, 128, 160, 192, 256); if (isset($thisfile_mpeg_audio['VBR_method']) && ($thisfile_mpeg_audio['VBR_method'] == 'Fraunhofer') && !empty($thisfile_mpeg_audio['VBR_quality'])) { $encoder_options = 'VBR q'.$thisfile_mpeg_audio['VBR_quality']; } 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))) { $encoder_options = $thisfile_mpeg_audio_lame['preset_used']; } elseif (!empty($thisfile_mpeg_audio_lame['vbr_quality'])) { static $KnownEncoderValues = array(); if (empty($KnownEncoderValues)) { //$KnownEncoderValues[abrbitrate_minbitrate][vbr_quality][raw_vbr_method][raw_noise_shaping][raw_stereo_mode][ath_type][lowpass_frequency] = 'preset name'; $KnownEncoderValues[0xFF][58][1][1][3][2][20500] = '--alt-preset insane'; // 3.90, 3.90.1, 3.92 $KnownEncoderValues[0xFF][58][1][1][3][2][20600] = '--alt-preset insane'; // 3.90.2, 3.90.3, 3.91 $KnownEncoderValues[0xFF][57][1][1][3][4][20500] = '--alt-preset insane'; // 3.94, 3.95 $KnownEncoderValues['**'][78][3][2][3][2][19500] = '--alt-preset extreme'; // 3.90, 3.90.1, 3.92 $KnownEncoderValues['**'][78][3][2][3][2][19600] = '--alt-preset extreme'; // 3.90.2, 3.91 $KnownEncoderValues['**'][78][3][1][3][2][19600] = '--alt-preset extreme'; // 3.90.3 $KnownEncoderValues['**'][78][4][2][3][2][19500] = '--alt-preset fast extreme'; // 3.90, 3.90.1, 3.92 $KnownEncoderValues['**'][78][4][2][3][2][19600] = '--alt-preset fast extreme'; // 3.90.2, 3.90.3, 3.91 $KnownEncoderValues['**'][78][3][2][3][4][19000] = '--alt-preset standard'; // 3.90, 3.90.1, 3.90.2, 3.91, 3.92 $KnownEncoderValues['**'][78][3][1][3][4][19000] = '--alt-preset standard'; // 3.90.3 $KnownEncoderValues['**'][78][4][2][3][4][19000] = '--alt-preset fast standard'; // 3.90, 3.90.1, 3.90.2, 3.91, 3.92 $KnownEncoderValues['**'][78][4][1][3][4][19000] = '--alt-preset fast standard'; // 3.90.3 $KnownEncoderValues['**'][88][4][1][3][3][19500] = '--r3mix'; // 3.90, 3.90.1, 3.92 $KnownEncoderValues['**'][88][4][1][3][3][19600] = '--r3mix'; // 3.90.2, 3.90.3, 3.91 $KnownEncoderValues['**'][67][4][1][3][4][18000] = '--r3mix'; // 3.94, 3.95 $KnownEncoderValues['**'][68][3][2][3][4][18000] = '--alt-preset medium'; // 3.90.3 $KnownEncoderValues['**'][68][4][2][3][4][18000] = '--alt-preset fast medium'; // 3.90.3 $KnownEncoderValues[0xFF][99][1][1][1][2][0] = '--preset studio'; // 3.90, 3.90.1, 3.90.2, 3.91, 3.92 $KnownEncoderValues[0xFF][58][2][1][3][2][20600] = '--preset studio'; // 3.90.3, 3.93.1 $KnownEncoderValues[0xFF][58][2][1][3][2][20500] = '--preset studio'; // 3.93 $KnownEncoderValues[0xFF][57][2][1][3][4][20500] = '--preset studio'; // 3.94, 3.95 $KnownEncoderValues[0xC0][88][1][1][1][2][0] = '--preset cd'; // 3.90, 3.90.1, 3.90.2, 3.91, 3.92 $KnownEncoderValues[0xC0][58][2][2][3][2][19600] = '--preset cd'; // 3.90.3, 3.93.1 $KnownEncoderValues[0xC0][58][2][2][3][2][19500] = '--preset cd'; // 3.93 $KnownEncoderValues[0xC0][57][2][1][3][4][19500] = '--preset cd'; // 3.94, 3.95 $KnownEncoderValues[0xA0][78][1][1][3][2][18000] = '--preset hifi'; // 3.90, 3.90.1, 3.90.2, 3.91, 3.92 $KnownEncoderValues[0xA0][58][2][2][3][2][18000] = '--preset hifi'; // 3.90.3, 3.93, 3.93.1 $KnownEncoderValues[0xA0][57][2][1][3][4][18000] = '--preset hifi'; // 3.94, 3.95 $KnownEncoderValues[0x80][67][1][1][3][2][18000] = '--preset tape'; // 3.90, 3.90.1, 3.90.2, 3.91, 3.92 $KnownEncoderValues[0x80][67][1][1][3][2][15000] = '--preset radio'; // 3.90, 3.90.1, 3.90.2, 3.91, 3.92 $KnownEncoderValues[0x70][67][1][1][3][2][15000] = '--preset fm'; // 3.90, 3.90.1, 3.90.2, 3.91, 3.92 $KnownEncoderValues[0x70][58][2][2][3][2][16000] = '--preset tape/radio/fm'; // 3.90.3, 3.93, 3.93.1 $KnownEncoderValues[0x70][57][2][1][3][4][16000] = '--preset tape/radio/fm'; // 3.94, 3.95 $KnownEncoderValues[0x38][58][2][2][0][2][10000] = '--preset voice'; // 3.90.3, 3.93, 3.93.1 $KnownEncoderValues[0x38][57][2][1][0][4][15000] = '--preset voice'; // 3.94, 3.95 $KnownEncoderValues[0x38][57][2][1][0][4][16000] = '--preset voice'; // 3.94a14 $KnownEncoderValues[0x28][65][1][1][0][2][7500] = '--preset mw-us'; // 3.90, 3.90.1, 3.92 $KnownEncoderValues[0x28][65][1][1][0][2][7600] = '--preset mw-us'; // 3.90.2, 3.91 $KnownEncoderValues[0x28][58][2][2][0][2][7000] = '--preset mw-us'; // 3.90.3, 3.93, 3.93.1 $KnownEncoderValues[0x28][57][2][1][0][4][10500] = '--preset mw-us'; // 3.94, 3.95 $KnownEncoderValues[0x28][57][2][1][0][4][11200] = '--preset mw-us'; // 3.94a14 $KnownEncoderValues[0x28][57][2][1][0][4][8800] = '--preset mw-us'; // 3.94a15 $KnownEncoderValues[0x18][58][2][2][0][2][4000] = '--preset phon+/lw/mw-eu/sw'; // 3.90.3, 3.93.1 $KnownEncoderValues[0x18][58][2][2][0][2][3900] = '--preset phon+/lw/mw-eu/sw'; // 3.93 $KnownEncoderValues[0x18][57][2][1][0][4][5900] = '--preset phon+/lw/mw-eu/sw'; // 3.94, 3.95 $KnownEncoderValues[0x18][57][2][1][0][4][6200] = '--preset phon+/lw/mw-eu/sw'; // 3.94a14 $KnownEncoderValues[0x18][57][2][1][0][4][3200] = '--preset phon+/lw/mw-eu/sw'; // 3.94a15 $KnownEncoderValues[0x10][58][2][2][0][2][3800] = '--preset phone'; // 3.90.3, 3.93.1 $KnownEncoderValues[0x10][58][2][2][0][2][3700] = '--preset phone'; // 3.93 $KnownEncoderValues[0x10][57][2][1][0][4][5600] = '--preset phone'; // 3.94, 3.95 } 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']])) { $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']]; } 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']])) { $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']]; } elseif ($info['audio']['bitrate_mode'] == 'vbr') { // http://gabriel.mp3-tech.org/mp3infotag.html // int Quality = (100 - 10 * gfp->VBR_q - gfp->quality)h $LAME_V_value = 10 - ceil($thisfile_mpeg_audio_lame['vbr_quality'] / 10); $LAME_q_value = 100 - $thisfile_mpeg_audio_lame['vbr_quality'] - ($LAME_V_value * 10); $encoder_options = '-V'.$LAME_V_value.' -q'.$LAME_q_value; } elseif ($info['audio']['bitrate_mode'] == 'cbr') { $encoder_options = strtoupper($info['audio']['bitrate_mode']).ceil($info['audio']['bitrate'] / 1000); } else { $encoder_options = strtoupper($info['audio']['bitrate_mode']); } } elseif (!empty($thisfile_mpeg_audio_lame['bitrate_abr'])) { $encoder_options = 'ABR'.$thisfile_mpeg_audio_lame['bitrate_abr']; } elseif (!empty($info['audio']['bitrate'])) { if ($info['audio']['bitrate_mode'] == 'cbr') { $encoder_options = strtoupper($info['audio']['bitrate_mode']).round($info['audio']['bitrate'] / 1000); } else { $encoder_options = strtoupper($info['audio']['bitrate_mode']); } } if (!empty($thisfile_mpeg_audio_lame['bitrate_min'])) { $encoder_options .= ' -b'.$thisfile_mpeg_audio_lame['bitrate_min']; } if (isset($thisfile_mpeg_audio['bitrate']) && $thisfile_mpeg_audio['bitrate'] === 'free') { $encoder_options .= ' --freeformat'; } 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; default: static $ExpectedResampledRate = array( 'phon+/lw/mw-eu/sw|16000' => 16000, 'mw-us|24000' => 24000, // 3.95 'mw-us|32000' => 32000, // 3.93 'mw-us|16000' => 16000, // 3.92 'phone|16000' => 16000, 'phone|11025' => 11025, // 3.94a15 'radio|32000' => 32000, // 3.94a15 'fm/radio|32000' => 32000, // 3.92 'fm|32000' => 32000, // 3.90 'voice|32000' => 32000); if (!isset($ExpectedResampledRate[$ExplodedOptions[1].'|'.$thisfile_mpeg_audio['sample_rate']])) { $encoder_options .= ' --resample '.$thisfile_mpeg_audio['sample_rate']; } break; } break; case '--r3mix': default: $encoder_options .= ' --resample '.$thisfile_mpeg_audio['sample_rate']; break; } break; } } } if (empty($encoder_options) && !empty($info['audio']['bitrate']) && !empty($info['audio']['bitrate_mode'])) { //$encoder_options = strtoupper($info['audio']['bitrate_mode']).ceil($info['audio']['bitrate'] / 1000); $encoder_options = strtoupper($info['audio']['bitrate_mode']); } return $encoder_options; } /** * @param int $offset * @param array $info * @param bool $recursivesearch * @param bool $ScanAsCBR * @param bool $FastMPEGheaderScan * * @return bool */ public function decodeMPEGaudioHeader($offset, &$info, $recursivesearch=true, $ScanAsCBR=false, $FastMPEGheaderScan=false) { static $MPEGaudioVersionLookup; static $MPEGaudioLayerLookup; static $MPEGaudioBitrateLookup; static $MPEGaudioFrequencyLookup; static $MPEGaudioChannelModeLookup; static $MPEGaudioModeExtensionLookup; static $MPEGaudioEmphasisLookup; if (empty($MPEGaudioVersionLookup)) { $MPEGaudioVersionLookup = self::MPEGaudioVersionArray(); $MPEGaudioLayerLookup = self::MPEGaudioLayerArray(); $MPEGaudioBitrateLookup = self::MPEGaudioBitrateArray(); $MPEGaudioFrequencyLookup = self::MPEGaudioFrequencyArray(); $MPEGaudioChannelModeLookup = self::MPEGaudioChannelModeArray(); $MPEGaudioModeExtensionLookup = self::MPEGaudioModeExtensionArray(); $MPEGaudioEmphasisLookup = self::MPEGaudioEmphasisArray(); } 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 $head4 = substr($headerstring, 0, 4); $head4_key = getid3_lib::PrintHexBytes($head4, true, false, false); static $MPEGaudioHeaderDecodeCache = array(); if (isset($MPEGaudioHeaderDecodeCache[$head4_key])) { $MPEGheaderRawArray = $MPEGaudioHeaderDecodeCache[$head4_key]; } else { $MPEGheaderRawArray = self::MPEGaudioHeaderDecode($head4); $MPEGaudioHeaderDecodeCache[$head4_key] = $MPEGheaderRawArray; } static $MPEGaudioHeaderValidCache = array(); if (!isset($MPEGaudioHeaderValidCache[$head4_key])) { // Not in cache //$MPEGaudioHeaderValidCache[$head4_key] = self::MPEGaudioHeaderValid($MPEGheaderRawArray, false, true); // allow badly-formatted freeformat (from LAME 3.90 - 3.93.1) $MPEGaudioHeaderValidCache[$head4_key] = self::MPEGaudioHeaderValid($MPEGheaderRawArray, false, false); } // shortcut if (!isset($info['mpeg']['audio'])) { $info['mpeg']['audio'] = array(); } $thisfile_mpeg_audio = &$info['mpeg']['audio']; if ($MPEGaudioHeaderValidCache[$head4_key]) { $thisfile_mpeg_audio['raw'] = $MPEGheaderRawArray; } else { $this->warning('Invalid MPEG audio header ('.getid3_lib::PrintHexBytes($head4).') at offset '.$offset); return false; } if (!$FastMPEGheaderScan) { $thisfile_mpeg_audio['version'] = $MPEGaudioVersionLookup[$thisfile_mpeg_audio['raw']['version']]; $thisfile_mpeg_audio['layer'] = $MPEGaudioLayerLookup[$thisfile_mpeg_audio['raw']['layer']]; $thisfile_mpeg_audio['channelmode'] = $MPEGaudioChannelModeLookup[$thisfile_mpeg_audio['raw']['channelmode']]; $thisfile_mpeg_audio['channels'] = (($thisfile_mpeg_audio['channelmode'] == 'mono') ? 1 : 2); $thisfile_mpeg_audio['sample_rate'] = $MPEGaudioFrequencyLookup[$thisfile_mpeg_audio['version']][$thisfile_mpeg_audio['raw']['sample_rate']]; $thisfile_mpeg_audio['protection'] = !$thisfile_mpeg_audio['raw']['protection']; $thisfile_mpeg_audio['private'] = (bool) $thisfile_mpeg_audio['raw']['private']; $thisfile_mpeg_audio['modeextension'] = $MPEGaudioModeExtensionLookup[$thisfile_mpeg_audio['layer']][$thisfile_mpeg_audio['raw']['modeextension']]; $thisfile_mpeg_audio['copyright'] = (bool) $thisfile_mpeg_audio['raw']['copyright']; $thisfile_mpeg_audio['original'] = (bool) $thisfile_mpeg_audio['raw']['original']; $thisfile_mpeg_audio['emphasis'] = $MPEGaudioEmphasisLookup[$thisfile_mpeg_audio['raw']['emphasis']]; $info['audio']['channels'] = $thisfile_mpeg_audio['channels']; $info['audio']['sample_rate'] = $thisfile_mpeg_audio['sample_rate']; 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')) { $info['audio']['dataformat'] = 'mp2'; switch ($thisfile_mpeg_audio['channelmode']) { 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 ($info['audio']['sample_rate'] > 0) { $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']); } $nextframetestoffset = $offset + 1; if ($thisfile_mpeg_audio['bitrate'] != 'free') { $info['audio']['bitrate'] = $thisfile_mpeg_audio['bitrate']; 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; } } $ExpectedNumberOfAudioBytes = 0; //////////////////////////////////////////////////////////////////////////////////// // Variable-bitrate headers 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 $thisfile_mpeg_audio['bitrate_mode'] = 'vbr'; $thisfile_mpeg_audio['VBR_method'] = 'Fraunhofer'; $info['audio']['codec'] = 'Fraunhofer'; $SideInfoData = substr($headerstring, 4 + 2, 32); $FraunhoferVBROffset = 36; $thisfile_mpeg_audio['VBR_encoder_version'] = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 4, 2)); // VbriVersion $thisfile_mpeg_audio['VBR_encoder_delay'] = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 6, 2)); // VbriDelay $thisfile_mpeg_audio['VBR_quality'] = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 8, 2)); // VbriQuality $thisfile_mpeg_audio['VBR_bytes'] = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 10, 4)); // VbriStreamBytes $thisfile_mpeg_audio['VBR_frames'] = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 14, 4)); // VbriStreamFrames $thisfile_mpeg_audio['VBR_seek_offsets'] = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 18, 2)); // VbriTableSize $thisfile_mpeg_audio['VBR_seek_scale'] = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 20, 2)); // VbriTableScale $thisfile_mpeg_audio['VBR_entry_bytes'] = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 22, 2)); // VbriEntryBytes $thisfile_mpeg_audio['VBR_entry_frames'] = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 24, 2)); // VbriEntryFrames $ExpectedNumberOfAudioBytes = $thisfile_mpeg_audio['VBR_bytes']; $previousbyteoffset = $offset; for ($i = 0; $i < $thisfile_mpeg_audio['VBR_seek_offsets']; $i++) { $Fraunhofer_OffsetN = getid3_lib::BigEndian2Int(substr($headerstring, $FraunhoferVBROffset, $thisfile_mpeg_audio['VBR_entry_bytes'])); $FraunhoferVBROffset += $thisfile_mpeg_audio['VBR_entry_bytes']; $thisfile_mpeg_audio['VBR_offsets_relative'][$i] = ($Fraunhofer_OffsetN * $thisfile_mpeg_audio['VBR_seek_scale']); $thisfile_mpeg_audio['VBR_offsets_absolute'][$i] = ($Fraunhofer_OffsetN * $thisfile_mpeg_audio['VBR_seek_scale']) + $previousbyteoffset; $previousbyteoffset += $Fraunhofer_OffsetN; } } else { // Xing VBR header is hardcoded 'Xing' at a offset 0x0D (13), 0x15 (21) or 0x24 (36) // depending on MPEG layer and number of channels $VBRidOffset = self::XingVBRidOffset($thisfile_mpeg_audio['version'], $thisfile_mpeg_audio['channelmode']); $SideInfoData = substr($headerstring, 4 + 2, $VBRidOffset - 4); 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['xing_flags_raw'] = getid3_lib::BigEndian2Int(substr($headerstring, $VBRidOffset + 4, 4)); $thisfile_mpeg_audio['xing_flags']['frames'] = (bool) ($thisfile_mpeg_audio['xing_flags_raw'] & 0x00000001); $thisfile_mpeg_audio['xing_flags']['bytes'] = (bool) ($thisfile_mpeg_audio['xing_flags_raw'] & 0x00000002); $thisfile_mpeg_audio['xing_flags']['toc'] = (bool) ($thisfile_mpeg_audio['xing_flags_raw'] & 0x00000004); $thisfile_mpeg_audio['xing_flags']['vbr_scale'] = (bool) ($thisfile_mpeg_audio['xing_flags_raw'] & 0x00000008); if ($thisfile_mpeg_audio['xing_flags']['frames']) { $thisfile_mpeg_audio['VBR_frames'] = getid3_lib::BigEndian2Int(substr($headerstring, $VBRidOffset + 8, 4)); //$thisfile_mpeg_audio['VBR_frames']--; // don't count header Xing/Info frame } if ($thisfile_mpeg_audio['xing_flags']['bytes']) { $thisfile_mpeg_audio['VBR_bytes'] = getid3_lib::BigEndian2Int(substr($headerstring, $VBRidOffset + 12, 4)); } //if (($thisfile_mpeg_audio['bitrate'] == 'free') && !empty($thisfile_mpeg_audio['VBR_frames']) && !empty($thisfile_mpeg_audio['VBR_bytes'])) { //if (!empty($thisfile_mpeg_audio['VBR_frames']) && !empty($thisfile_mpeg_audio['VBR_bytes'])) { if (!empty($thisfile_mpeg_audio['VBR_frames'])) { $used_filesize = 0; if (!empty($thisfile_mpeg_audio['VBR_bytes'])) { $used_filesize = $thisfile_mpeg_audio['VBR_bytes']; } elseif (!empty($info['filesize'])) { $used_filesize = $info['filesize']; $used_filesize -= (isset($info['id3v2']['headerlength']) ? intval($info['id3v2']['headerlength']) : 0); $used_filesize -= (isset($info['id3v1']) ? 128 : 0); $used_filesize -= (isset($info['tag_offset_end']) ? $info['tag_offset_end'] - $info['tag_offset_start'] : 0); $this->warning('MP3.Xing header missing VBR_bytes, assuming MPEG audio portion of file is '.number_format($used_filesize).' bytes'); } $framelengthfloat = $used_filesize / $thisfile_mpeg_audio['VBR_frames']; if ($thisfile_mpeg_audio['layer'] == '1') { // BitRate = (((FrameLengthInBytes / 4) - Padding) * SampleRate) / 12 //$info['audio']['bitrate'] = ((($framelengthfloat / 4) - intval($thisfile_mpeg_audio['padding'])) * $thisfile_mpeg_audio['sample_rate']) / 12; $info['audio']['bitrate'] = ($framelengthfloat / 4) * $thisfile_mpeg_audio['sample_rate'] * (2 / $info['audio']['channels']) / 12; } else { // Bitrate = ((FrameLengthInBytes - Padding) * SampleRate) / 144 //$info['audio']['bitrate'] = (($framelengthfloat - intval($thisfile_mpeg_audio['padding'])) * $thisfile_mpeg_audio['sample_rate']) / 144; $info['audio']['bitrate'] = $framelengthfloat * $thisfile_mpeg_audio['sample_rate'] * (2 / $info['audio']['channels']) / 144; } $thisfile_mpeg_audio['framelength'] = floor($framelengthfloat); } if ($thisfile_mpeg_audio['xing_flags']['toc']) { $LAMEtocData = substr($headerstring, $VBRidOffset + 16, 100); for ($i = 0; $i < 100; $i++) { $thisfile_mpeg_audio['toc'][$i] = ord($LAMEtocData[$i]); } } if ($thisfile_mpeg_audio['xing_flags']['vbr_scale']) { $thisfile_mpeg_audio['VBR_scale'] = getid3_lib::BigEndian2Int(substr($headerstring, $VBRidOffset + 116, 4)); } // http://gabriel.mp3-tech.org/mp3infotag.html if (substr($headerstring, $VBRidOffset + 120, 4) == 'LAME') { // shortcut $thisfile_mpeg_audio['LAME'] = array(); $thisfile_mpeg_audio_lame = &$thisfile_mpeg_audio['LAME']; $thisfile_mpeg_audio_lame['long_version'] = substr($headerstring, $VBRidOffset + 120, 20); $thisfile_mpeg_audio_lame['short_version'] = substr($thisfile_mpeg_audio_lame['long_version'], 0, 9); //$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; // shortcuts $thisfile_mpeg_audio_lame['RGAD'] = array('track'=>array(), 'album'=>array()); $thisfile_mpeg_audio_lame_RGAD = &$thisfile_mpeg_audio_lame['RGAD']; $thisfile_mpeg_audio_lame_RGAD_track = &$thisfile_mpeg_audio_lame_RGAD['track']; $thisfile_mpeg_audio_lame_RGAD_album = &$thisfile_mpeg_audio_lame_RGAD['album']; $thisfile_mpeg_audio_lame['raw'] = array(); $thisfile_mpeg_audio_lame_raw = &$thisfile_mpeg_audio_lame['raw']; // 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 $9C-$A4 Encoder short VersionString $thisfile_mpeg_audio_lame['short_version'] = substr($headerstring, $LAMEtagOffsetContant + 0x9C, 9); // byte $A5 Info Tag revision + VBR method $LAMEtagRevisionVBRmethod = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xA5, 1)); $thisfile_mpeg_audio_lame['tag_revision'] = ($LAMEtagRevisionVBRmethod & 0xF0) >> 4; $thisfile_mpeg_audio_lame_raw['vbr_method'] = $LAMEtagRevisionVBRmethod & 0x0F; $thisfile_mpeg_audio_lame['vbr_method'] = self::LAMEvbrMethodLookup($thisfile_mpeg_audio_lame_raw['vbr_method']); $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' // byte $A6 Lowpass filter value $thisfile_mpeg_audio_lame['lowpass_frequency'] = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xA6, 1)) * 100; // 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']); } $thisfile_mpeg_audio_lame_raw['RGAD_track'] = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xAB, 2)); $thisfile_mpeg_audio_lame_raw['RGAD_album'] = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xAD, 2)); if ($thisfile_mpeg_audio_lame_raw['RGAD_track'] != 0) { $thisfile_mpeg_audio_lame_RGAD_track['raw']['name'] = ($thisfile_mpeg_audio_lame_raw['RGAD_track'] & 0xE000) >> 13; $thisfile_mpeg_audio_lame_RGAD_track['raw']['originator'] = ($thisfile_mpeg_audio_lame_raw['RGAD_track'] & 0x1C00) >> 10; $thisfile_mpeg_audio_lame_RGAD_track['raw']['sign_bit'] = ($thisfile_mpeg_audio_lame_raw['RGAD_track'] & 0x0200) >> 9; $thisfile_mpeg_audio_lame_RGAD_track['raw']['gain_adjust'] = $thisfile_mpeg_audio_lame_raw['RGAD_track'] & 0x01FF; $thisfile_mpeg_audio_lame_RGAD_track['name'] = getid3_lib::RGADnameLookup($thisfile_mpeg_audio_lame_RGAD_track['raw']['name']); $thisfile_mpeg_audio_lame_RGAD_track['originator'] = getid3_lib::RGADoriginatorLookup($thisfile_mpeg_audio_lame_RGAD_track['raw']['originator']); $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']); if (!empty($thisfile_mpeg_audio_lame_RGAD['peak_amplitude'])) { $info['replay_gain']['track']['peak'] = $thisfile_mpeg_audio_lame_RGAD['peak_amplitude']; } $info['replay_gain']['track']['originator'] = $thisfile_mpeg_audio_lame_RGAD_track['originator']; $info['replay_gain']['track']['adjustment'] = $thisfile_mpeg_audio_lame_RGAD_track['gain_db']; } else { unset($thisfile_mpeg_audio_lame_RGAD['track']); } if ($thisfile_mpeg_audio_lame_raw['RGAD_album'] != 0) { $thisfile_mpeg_audio_lame_RGAD_album['raw']['name'] = ($thisfile_mpeg_audio_lame_raw['RGAD_album'] & 0xE000) >> 13; $thisfile_mpeg_audio_lame_RGAD_album['raw']['originator'] = ($thisfile_mpeg_audio_lame_raw['RGAD_album'] & 0x1C00) >> 10; $thisfile_mpeg_audio_lame_RGAD_album['raw']['sign_bit'] = ($thisfile_mpeg_audio_lame_raw['RGAD_album'] & 0x0200) >> 9; $thisfile_mpeg_audio_lame_RGAD_album['raw']['gain_adjust'] = $thisfile_mpeg_audio_lame_raw['RGAD_album'] & 0x01FF; $thisfile_mpeg_audio_lame_RGAD_album['name'] = getid3_lib::RGADnameLookup($thisfile_mpeg_audio_lame_RGAD_album['raw']['name']); $thisfile_mpeg_audio_lame_RGAD_album['originator'] = getid3_lib::RGADoriginatorLookup($thisfile_mpeg_audio_lame_RGAD_album['raw']['originator']); $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']); if (!empty($thisfile_mpeg_audio_lame_RGAD['peak_amplitude'])) { $info['replay_gain']['album']['peak'] = $thisfile_mpeg_audio_lame_RGAD['peak_amplitude']; } $info['replay_gain']['album']['originator'] = $thisfile_mpeg_audio_lame_RGAD_album['originator']; $info['replay_gain']['album']['adjustment'] = $thisfile_mpeg_audio_lame_RGAD_album['gain_db']; } else { unset($thisfile_mpeg_audio_lame_RGAD['album']); } if (empty($thisfile_mpeg_audio_lame_RGAD)) { unset($thisfile_mpeg_audio_lame['RGAD']); } // byte $AF Encoding flags + ATH Type $EncodingFlagsATHtype = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xAF, 1)); $thisfile_mpeg_audio_lame['encoding_flags']['nspsytune'] = (bool) ($EncodingFlagsATHtype & 0x10); $thisfile_mpeg_audio_lame['encoding_flags']['nssafejoint'] = (bool) ($EncodingFlagsATHtype & 0x20); $thisfile_mpeg_audio_lame['encoding_flags']['nogap_next'] = (bool) ($EncodingFlagsATHtype & 0x40); $thisfile_mpeg_audio_lame['encoding_flags']['nogap_prev'] = (bool) ($EncodingFlagsATHtype & 0x80); $thisfile_mpeg_audio_lame['ath_type'] = $EncodingFlagsATHtype & 0x0F; // byte $B0 if ABR {specified bitrate} else {minimal bitrate} $thisfile_mpeg_audio_lame['raw']['abrbitrate_minbitrate'] = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB0, 1)); if ($thisfile_mpeg_audio_lame_raw['vbr_method'] == 2) { // Average BitRate (ABR) $thisfile_mpeg_audio_lame['bitrate_abr'] = $thisfile_mpeg_audio_lame['raw']['abrbitrate_minbitrate']; } elseif ($thisfile_mpeg_audio_lame_raw['vbr_method'] == 1) { // Constant BitRate (CBR) // ignore } elseif ($thisfile_mpeg_audio_lame['raw']['abrbitrate_minbitrate'] > 0) { // Variable BitRate (VBR) - minimum bitrate $thisfile_mpeg_audio_lame['bitrate_min'] = $thisfile_mpeg_audio_lame['raw']['abrbitrate_minbitrate']; } // bytes $B1-$B3 Encoder delays $EncoderDelays = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB1, 3)); $thisfile_mpeg_audio_lame['encoder_delay'] = ($EncoderDelays & 0xFFF000) >> 12; $thisfile_mpeg_audio_lame['end_padding'] = $EncoderDelays & 0x000FFF; // byte $B4 Misc $MiscByte = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB4, 1)); $thisfile_mpeg_audio_lame_raw['noise_shaping'] = ($MiscByte & 0x03); $thisfile_mpeg_audio_lame_raw['stereo_mode'] = ($MiscByte & 0x1C) >> 2; $thisfile_mpeg_audio_lame_raw['not_optimal_quality'] = ($MiscByte & 0x20) >> 5; $thisfile_mpeg_audio_lame_raw['source_sample_freq'] = ($MiscByte & 0xC0) >> 6; $thisfile_mpeg_audio_lame['noise_shaping'] = $thisfile_mpeg_audio_lame_raw['noise_shaping']; $thisfile_mpeg_audio_lame['stereo_mode'] = self::LAMEmiscStereoModeLookup($thisfile_mpeg_audio_lame_raw['stereo_mode']); $thisfile_mpeg_audio_lame['not_optimal_quality'] = (bool) $thisfile_mpeg_audio_lame_raw['not_optimal_quality']; $thisfile_mpeg_audio_lame['source_sample_freq'] = self::LAMEmiscSourceSampleFrequencyLookup($thisfile_mpeg_audio_lame_raw['source_sample_freq']); // byte $B5 MP3 Gain $thisfile_mpeg_audio_lame_raw['mp3_gain'] = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB5, 1), false, true); $thisfile_mpeg_audio_lame['mp3_gain_db'] = (getid3_lib::RGADamplitude2dB(2) / 4) * $thisfile_mpeg_audio_lame_raw['mp3_gain']; $thisfile_mpeg_audio_lame['mp3_gain_factor'] = pow(2, ($thisfile_mpeg_audio_lame['mp3_gain_db'] / 6)); // bytes $B6-$B7 Preset and surround info $PresetSurroundBytes = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB6, 2)); // Reserved = ($PresetSurroundBytes & 0xC000); $thisfile_mpeg_audio_lame_raw['surround_info'] = ($PresetSurroundBytes & 0x3800); $thisfile_mpeg_audio_lame['surround_info'] = self::LAMEsurroundInfoLookup($thisfile_mpeg_audio_lame_raw['surround_info']); $thisfile_mpeg_audio_lame['preset_used_id'] = ($PresetSurroundBytes & 0x07FF); $thisfile_mpeg_audio_lame['preset_used'] = self::LAMEpresetUsedLookup($thisfile_mpeg_audio_lame); if (!empty($thisfile_mpeg_audio_lame['preset_used_id']) && empty($thisfile_mpeg_audio_lame['preset_used'])) { $this->warning('Unknown LAME preset used ('.$thisfile_mpeg_audio_lame['preset_used_id'].') - please report to info@getid3.org'); } if (($thisfile_mpeg_audio_lame['short_version'] == 'LAME3.90.') && !empty($thisfile_mpeg_audio_lame['preset_used_id'])) { // this may change if 3.90.4 ever comes out $thisfile_mpeg_audio_lame['short_version'] = 'LAME3.90.3'; } // bytes $B8-$BB MusicLength $thisfile_mpeg_audio_lame['audio_bytes'] = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB8, 4)); $ExpectedNumberOfAudioBytes = (($thisfile_mpeg_audio_lame['audio_bytes'] > 0) ? $thisfile_mpeg_audio_lame['audio_bytes'] : $thisfile_mpeg_audio['VBR_bytes']); // bytes $BC-$BD MusicCRC $thisfile_mpeg_audio_lame['music_crc'] = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xBC, 2)); // bytes $BE-$BF CRC-16 of Info Tag $thisfile_mpeg_audio_lame['lame_tag_crc'] = getid3_lib::BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xBE, 2)); // LAME CBR if ($thisfile_mpeg_audio_lame_raw['vbr_method'] == 1 && $thisfile_mpeg_audio['bitrate'] !== 'free') { $thisfile_mpeg_audio['bitrate_mode'] = 'cbr'; $thisfile_mpeg_audio['bitrate'] = self::ClosestStandardMP3Bitrate($thisfile_mpeg_audio['bitrate']); $info['audio']['bitrate'] = $thisfile_mpeg_audio['bitrate']; //if (empty($thisfile_mpeg_audio['bitrate']) || (!empty($thisfile_mpeg_audio_lame['bitrate_min']) && ($thisfile_mpeg_audio_lame['bitrate_min'] != 255))) { // $thisfile_mpeg_audio['bitrate'] = $thisfile_mpeg_audio_lame['bitrate_min']; //} } } } } } else { // 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)'); } } } if (($thisfile_mpeg_audio['bitrate'] == 'free') && empty($info['audio']['bitrate'])) { if (($offset == $info['avdataoffset']) && empty($thisfile_mpeg_audio['VBR_frames'])) { $framebytelength = $this->FreeFormatFrameLength($offset, true); if ($framebytelength > 0) { $thisfile_mpeg_audio['framelength'] = $framebytelength; if ($thisfile_mpeg_audio['layer'] == '1') { // BitRate = (((FrameLengthInBytes / 4) - Padding) * SampleRate) / 12 $info['audio']['bitrate'] = ((($framebytelength / 4) - intval($thisfile_mpeg_audio['padding'])) * $thisfile_mpeg_audio['sample_rate']) / 12; } else { // Bitrate = ((FrameLengthInBytes - Padding) * SampleRate) / 144 $info['audio']['bitrate'] = (($framebytelength - intval($thisfile_mpeg_audio['padding'])) * $thisfile_mpeg_audio['sample_rate']) / 144; } } else { $this->error('Error calculating frame length of free-format MP3 without Xing/LAME header'); } } } if (isset($thisfile_mpeg_audio['VBR_frames']) ? $thisfile_mpeg_audio['VBR_frames'] : '') { switch ($thisfile_mpeg_audio['bitrate_mode']) { case 'vbr': case 'abr': $bytes_per_frame = 1152; if (($thisfile_mpeg_audio['version'] == '1') && ($thisfile_mpeg_audio['layer'] == 1)) { $bytes_per_frame = 384; } elseif ((($thisfile_mpeg_audio['version'] == '2') || ($thisfile_mpeg_audio['version'] == '2.5')) && ($thisfile_mpeg_audio['layer'] == 3)) { $bytes_per_frame = 576; } $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); if ($thisfile_mpeg_audio['VBR_bitrate'] > 0) { $info['audio']['bitrate'] = $thisfile_mpeg_audio['VBR_bitrate']; $thisfile_mpeg_audio['bitrate'] = $thisfile_mpeg_audio['VBR_bitrate']; // to avoid confusion } break; } } // End variable-bitrate headers //////////////////////////////////////////////////////////////////////////////////// if ($recursivesearch) { if (!$this->RecursiveFrameScanning($offset, $nextframetestoffset, $ScanAsCBR)) { return false; } if (!empty($this->getid3->info['mp3_validity_check_bitrates']) && !empty($thisfile_mpeg_audio['bitrate_mode']) && ($thisfile_mpeg_audio['bitrate_mode'] == 'vbr') && !empty($thisfile_mpeg_audio['VBR_bitrate'])) { // https://github.com/JamesHeinrich/getID3/issues/287 if (count(array_keys($this->getid3->info['mp3_validity_check_bitrates'])) == 1) { list($cbr_bitrate_in_short_scan) = array_keys($this->getid3->info['mp3_validity_check_bitrates']); $deviation_cbr_from_header_bitrate = abs($thisfile_mpeg_audio['VBR_bitrate'] - $cbr_bitrate_in_short_scan) / $cbr_bitrate_in_short_scan; if ($deviation_cbr_from_header_bitrate < 0.01) { // VBR header bitrate may differ slightly from true bitrate of frames, perhaps accounting for overhead of VBR header frame itself? // If measured CBR bitrate is within 1% of specified bitrate in VBR header then assume that file is truly CBR $thisfile_mpeg_audio['bitrate_mode'] = 'cbr'; //$this->warning('VBR header ignored, assuming CBR '.round($cbr_bitrate_in_short_scan / 1000).'kbps based on scan of '.$this->mp3_valid_check_frames.' frames'); } } } if (isset($this->getid3->info['mp3_validity_check_bitrates'])) { unset($this->getid3->info['mp3_validity_check_bitrates']); } } //if (false) { // // experimental side info parsing section - not returning anything useful yet // // $SideInfoBitstream = getid3_lib::BigEndian2Bin($SideInfoData); // $SideInfoOffset = 0; // // if ($thisfile_mpeg_audio['version'] == '1') { // if ($thisfile_mpeg_audio['channelmode'] == 'mono') { // // MPEG-1 (mono) // $thisfile_mpeg_audio['side_info']['main_data_begin'] = substr($SideInfoBitstream, $SideInfoOffset, 9); // $SideInfoOffset += 9; // $SideInfoOffset += 5; // } else { // // MPEG-1 (stereo, joint-stereo, dual-channel) // $thisfile_mpeg_audio['side_info']['main_data_begin'] = substr($SideInfoBitstream, $SideInfoOffset, 9); // $SideInfoOffset += 9; // $SideInfoOffset += 3; // } // } else { // 2 or 2.5 // if ($thisfile_mpeg_audio['channelmode'] == 'mono') { // // MPEG-2, MPEG-2.5 (mono) // $thisfile_mpeg_audio['side_info']['main_data_begin'] = substr($SideInfoBitstream, $SideInfoOffset, 8); // $SideInfoOffset += 8; // $SideInfoOffset += 1; // } else { // // MPEG-2, MPEG-2.5 (stereo, joint-stereo, dual-channel) // $thisfile_mpeg_audio['side_info']['main_data_begin'] = substr($SideInfoBitstream, $SideInfoOffset, 8); // $SideInfoOffset += 8; // $SideInfoOffset += 2; // } // } // // if ($thisfile_mpeg_audio['version'] == '1') { // for ($channel = 0; $channel < $info['audio']['channels']; $channel++) { // for ($scfsi_band = 0; $scfsi_band < 4; $scfsi_band++) { // $thisfile_mpeg_audio['scfsi'][$channel][$scfsi_band] = substr($SideInfoBitstream, $SideInfoOffset, 1); // $SideInfoOffset += 2; // } // } // } // for ($granule = 0; $granule < (($thisfile_mpeg_audio['version'] == '1') ? 2 : 1); $granule++) { // for ($channel = 0; $channel < $info['audio']['channels']; $channel++) { // $thisfile_mpeg_audio['part2_3_length'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 12); // $SideInfoOffset += 12; // $thisfile_mpeg_audio['big_values'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 9); // $SideInfoOffset += 9; // $thisfile_mpeg_audio['global_gain'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 8); // $SideInfoOffset += 8; // if ($thisfile_mpeg_audio['version'] == '1') { // $thisfile_mpeg_audio['scalefac_compress'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 4); // $SideInfoOffset += 4; // } else { // $thisfile_mpeg_audio['scalefac_compress'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 9); // $SideInfoOffset += 9; // } // $thisfile_mpeg_audio['window_switching_flag'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 1); // $SideInfoOffset += 1; // // if ($thisfile_mpeg_audio['window_switching_flag'][$granule][$channel] == '1') { // // $thisfile_mpeg_audio['block_type'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 2); // $SideInfoOffset += 2; // $thisfile_mpeg_audio['mixed_block_flag'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 1); // $SideInfoOffset += 1; // // for ($region = 0; $region < 2; $region++) { // $thisfile_mpeg_audio['table_select'][$granule][$channel][$region] = substr($SideInfoBitstream, $SideInfoOffset, 5); // $SideInfoOffset += 5; // } // $thisfile_mpeg_audio['table_select'][$granule][$channel][2] = 0; // // for ($window = 0; $window < 3; $window++) { // $thisfile_mpeg_audio['subblock_gain'][$granule][$channel][$window] = substr($SideInfoBitstream, $SideInfoOffset, 3); // $SideInfoOffset += 3; // } // // } else { // // for ($region = 0; $region < 3; $region++) { // $thisfile_mpeg_audio['table_select'][$granule][$channel][$region] = substr($SideInfoBitstream, $SideInfoOffset, 5); // $SideInfoOffset += 5; // } // // $thisfile_mpeg_audio['region0_count'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 4); // $SideInfoOffset += 4; // $thisfile_mpeg_audio['region1_count'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 3); // $SideInfoOffset += 3; // $thisfile_mpeg_audio['block_type'][$granule][$channel] = 0; // } // // if ($thisfile_mpeg_audio['version'] == '1') { // $thisfile_mpeg_audio['preflag'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 1); // $SideInfoOffset += 1; // } // $thisfile_mpeg_audio['scalefac_scale'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 1); // $SideInfoOffset += 1; // $thisfile_mpeg_audio['count1table_select'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 1); // $SideInfoOffset += 1; // } // } //} return true; } /** * @param int $offset * @param int $nextframetestoffset * @param bool $ScanAsCBR * * @return bool */ public function RecursiveFrameScanning(&$offset, &$nextframetestoffset, $ScanAsCBR) { $info = &$this->getid3->info; $firstframetestarray = array('error' => array(), 'warning'=> array(), 'avdataend' => $info['avdataend'], 'avdataoffset' => $info['avdataoffset']); $this->decodeMPEGaudioHeader($offset, $firstframetestarray, false); $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; } } elseif (!empty($firstframetestarray['mpeg']['audio']['framelength']) && (($nextframetestoffset + $firstframetestarray['mpeg']['audio']['framelength']) > $info['avdataend'])) { // 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; $this->fseek($offset); $MPEGaudioData = $this->fread(32768); $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]; } $framelength = false; $framelength1 = strpos($MPEGaudioData, $SyncPattern1, 4); $framelength2 = strpos($MPEGaudioData, $SyncPattern2, 4); if ($framelength1 > 4) { $framelength = $framelength1; } if (($framelength2 > 4) && ($framelength2 < $framelength1)) { $framelength = $framelength2; } if (!$framelength) { // 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; } /** * @return bool */ public function getOnlyMPEGaudioInfoBruteForce() { $MPEGaudioHeaderDecodeCache = array(); $MPEGaudioHeaderValidCache = array(); $MPEGaudioHeaderLengthCache = array(); $MPEGaudioVersionLookup = self::MPEGaudioVersionArray(); $MPEGaudioLayerLookup = self::MPEGaudioLayerArray(); $MPEGaudioBitrateLookup = self::MPEGaudioBitrateArray(); $MPEGaudioFrequencyLookup = self::MPEGaudioFrequencyArray(); $MPEGaudioChannelModeLookup = self::MPEGaudioChannelModeArray(); $MPEGaudioModeExtensionLookup = self::MPEGaudioModeExtensionArray(); $MPEGaudioEmphasisLookup = self::MPEGaudioEmphasisArray(); $LongMPEGversionLookup = array(); $LongMPEGlayerLookup = array(); $LongMPEGbitrateLookup = array(); $LongMPEGpaddingLookup = array(); $LongMPEGfrequencyLookup = array(); $Distribution = array(); $Distribution['bitrate'] = array(); $Distribution['frequency'] = array(); $Distribution['layer'] = array(); $Distribution['version'] = array(); $Distribution['padding'] = array(); $info = &$this->getid3->info; $this->fseek($info['avdataoffset']); $max_frames_scan = 5000; $frames_scanned = 0; $previousvalidframe = $info['avdataoffset']; while ($this->ftell() < $info['avdataend']) { set_time_limit(30); $head4 = $this->fread(4); if (strlen($head4) < 4) { break; } if ($head4[0] != "\xFF") { for ($i = 1; $i < 4; $i++) { if ($head4[$i] == "\xFF") { $this->fseek($i - 4, SEEK_CUR); continue 2; } } continue; } if (!isset($MPEGaudioHeaderDecodeCache[$head4])) { $MPEGaudioHeaderDecodeCache[$head4] = self::MPEGaudioHeaderDecode($head4); } if (!isset($MPEGaudioHeaderValidCache[$head4])) { $MPEGaudioHeaderValidCache[$head4] = self::MPEGaudioHeaderValid($MPEGaudioHeaderDecodeCache[$head4], false, false); } if ($MPEGaudioHeaderValidCache[$head4]) { if (!isset($MPEGaudioHeaderLengthCache[$head4])) { $LongMPEGversionLookup[$head4] = $MPEGaudioVersionLookup[$MPEGaudioHeaderDecodeCache[$head4]['version']]; $LongMPEGlayerLookup[$head4] = $MPEGaudioLayerLookup[$MPEGaudioHeaderDecodeCache[$head4]['layer']]; $LongMPEGbitrateLookup[$head4] = $MPEGaudioBitrateLookup[$LongMPEGversionLookup[$head4]][$LongMPEGlayerLookup[$head4]][$MPEGaudioHeaderDecodeCache[$head4]['bitrate']]; $LongMPEGpaddingLookup[$head4] = (bool) $MPEGaudioHeaderDecodeCache[$head4]['padding']; $LongMPEGfrequencyLookup[$head4] = $MPEGaudioFrequencyLookup[$LongMPEGversionLookup[$head4]][$MPEGaudioHeaderDecodeCache[$head4]['sample_rate']]; $MPEGaudioHeaderLengthCache[$head4] = self::MPEGaudioFrameLength( $LongMPEGbitrateLookup[$head4], $LongMPEGversionLookup[$head4], $LongMPEGlayerLookup[$head4], $LongMPEGpaddingLookup[$head4], $LongMPEGfrequencyLookup[$head4]); } if ($MPEGaudioHeaderLengthCache[$head4] > 4) { $WhereWeWere = $this->ftell(); $this->fseek($MPEGaudioHeaderLengthCache[$head4] - 4, SEEK_CUR); $next4 = $this->fread(4); if ($next4[0] == "\xFF") { if (!isset($MPEGaudioHeaderDecodeCache[$next4])) { $MPEGaudioHeaderDecodeCache[$next4] = self::MPEGaudioHeaderDecode($next4); } if (!isset($MPEGaudioHeaderValidCache[$next4])) { $MPEGaudioHeaderValidCache[$next4] = self::MPEGaudioHeaderValid($MPEGaudioHeaderDecodeCache[$next4], false, false); } if ($MPEGaudioHeaderValidCache[$next4]) { $this->fseek(-4, SEEK_CUR); $Distribution['bitrate'][$LongMPEGbitrateLookup[$head4]] = isset($Distribution['bitrate'][$LongMPEGbitrateLookup[$head4]]) ? ++$Distribution['bitrate'][$LongMPEGbitrateLookup[$head4]] : 1; $Distribution['layer'][$LongMPEGlayerLookup[$head4]] = isset($Distribution['layer'][$LongMPEGlayerLookup[$head4]]) ? ++$Distribution['layer'][$LongMPEGlayerLookup[$head4]] : 1; $Distribution['version'][$LongMPEGversionLookup[$head4]] = isset($Distribution['version'][$LongMPEGversionLookup[$head4]]) ? ++$Distribution['version'][$LongMPEGversionLookup[$head4]] : 1; $Distribution['padding'][intval($LongMPEGpaddingLookup[$head4])] = isset($Distribution['padding'][intval($LongMPEGpaddingLookup[$head4])]) ? ++$Distribution['padding'][intval($LongMPEGpaddingLookup[$head4])] : 1; $Distribution['frequency'][$LongMPEGfrequencyLookup[$head4]] = isset($Distribution['frequency'][$LongMPEGfrequencyLookup[$head4]]) ? ++$Distribution['frequency'][$LongMPEGfrequencyLookup[$head4]] : 1; if (++$frames_scanned >= $max_frames_scan) { $pct_data_scanned = getid3_lib::SafeDiv($this->ftell() - $info['avdataoffset'], $info['avdataend'] - $info['avdataoffset']); $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.'); foreach ($Distribution as $key1 => $value1) { foreach ($value1 as $key2 => $value2) { $Distribution[$key1][$key2] = $pct_data_scanned ? round($value2 / $pct_data_scanned) : 1; } } break; } continue; } } unset($next4); $this->fseek($WhereWeWere - 3); } } } foreach ($Distribution as $key => $value) { ksort($Distribution[$key], SORT_NUMERIC); } ksort($Distribution['version'], SORT_STRING); $info['mpeg']['audio']['bitrate_distribution'] = $Distribution['bitrate']; $info['mpeg']['audio']['frequency_distribution'] = $Distribution['frequency']; $info['mpeg']['audio']['layer_distribution'] = $Distribution['layer']; $info['mpeg']['audio']['version_distribution'] = $Distribution['version']; $info['mpeg']['audio']['padding_distribution'] = $Distribution['padding']; if (count($Distribution['version']) > 1) { $this->error('Corrupt file - more than one MPEG version detected'); } if (count($Distribution['layer']) > 1) { $this->error('Corrupt file - more than one MPEG layer detected'); } if (count($Distribution['frequency']) > 1) { $this->error('Corrupt file - more than one MPEG sample rate detected'); } $bittotal = 0; foreach ($Distribution['bitrate'] as $bitratevalue => $bitratecount) { if ($bitratevalue != 'free') { $bittotal += ($bitratevalue * $bitratecount); } } $info['mpeg']['audio']['frame_count'] = array_sum($Distribution['bitrate']); if ($info['mpeg']['audio']['frame_count'] == 0) { $this->error('no MPEG audio frames found'); return false; } $info['mpeg']['audio']['bitrate'] = ($bittotal / $info['mpeg']['audio']['frame_count']); $info['mpeg']['audio']['bitrate_mode'] = ((count($Distribution['bitrate']) > 0) ? 'vbr' : 'cbr'); $info['mpeg']['audio']['sample_rate'] = getid3_lib::array_max($Distribution['frequency'], true); $info['audio']['bitrate'] = $info['mpeg']['audio']['bitrate']; $info['audio']['bitrate_mode'] = $info['mpeg']['audio']['bitrate_mode']; $info['audio']['sample_rate'] = $info['mpeg']['audio']['sample_rate']; $info['audio']['dataformat'] = 'mp'.getid3_lib::array_max($Distribution['layer'], true); $info['fileformat'] = $info['audio']['dataformat']; return true; } /** * @param int $avdataoffset * @param bool $BitrateHistogram * * @return bool */ public function getOnlyMPEGaudioInfo($avdataoffset, $BitrateHistogram=false) { // looks for synch, decodes MPEG audio header $info = &$this->getid3->info; static $MPEGaudioVersionLookup; static $MPEGaudioLayerLookup; static $MPEGaudioBitrateLookup; if (empty($MPEGaudioVersionLookup)) { $MPEGaudioVersionLookup = self::MPEGaudioVersionArray(); $MPEGaudioLayerLookup = self::MPEGaudioLayerArray(); $MPEGaudioBitrateLookup = self::MPEGaudioBitrateArray(); } $this->fseek($avdataoffset); $sync_seek_buffer_size = min(128 * 1024, $info['avdataend'] - $avdataoffset); if ($sync_seek_buffer_size <= 0) { $this->error('Invalid $sync_seek_buffer_size at offset '.$avdataoffset); return false; } $header = $this->fread($sync_seek_buffer_size); $sync_seek_buffer_size = strlen($header); $SynchSeekOffset = 0; $SyncSeekAttempts = 0; $SyncSeekAttemptsMax = 1000; $FirstFrameThisfileInfo = null; while ($SynchSeekOffset < $sync_seek_buffer_size) { if ((($avdataoffset + $SynchSeekOffset) < $info['avdataend']) && !$this->feof()) { 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; } if ($BitrateHistogram) { $info['mpeg']['audio']['stereo_distribution'] = array('stereo'=>0, 'joint stereo'=>0, 'dual channel'=>0, 'mono'=>0); $info['mpeg']['audio']['version_distribution'] = array('1'=>0, '2'=>0, '2.5'=>0); if ($info['mpeg']['audio']['version'] == '1') { if ($info['mpeg']['audio']['layer'] == 3) { $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); } elseif ($info['mpeg']['audio']['layer'] == 2) { $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); } elseif ($info['mpeg']['audio']['layer'] == 1) { $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); } } elseif ($info['mpeg']['audio']['layer'] == 1) { $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); } else { $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); } $dummy = array('error'=>$info['error'], 'warning'=>$info['warning'], 'avdataend'=>$info['avdataend'], 'avdataoffset'=>$info['avdataoffset']); $synchstartoffset = $info['avdataoffset']; $this->fseek($info['avdataoffset']); // you can play with these numbers: $max_frames_scan = 50000; $max_scan_segments = 10; // don't play with these numbers: $FastMode = false; $SynchErrorsFound = 0; $frames_scanned = 0; $this_scan_segment = 0; $frames_scan_per_segment = ceil($max_frames_scan / $max_scan_segments); $pct_data_scanned = 0; for ($current_segment = 0; $current_segment < $max_scan_segments; $current_segment++) { $frames_scanned_this_segment = 0; $scan_start_offset = array(); if ($this->ftell() >= $info['avdataend']) { break; } $scan_start_offset[$current_segment] = max($this->ftell(), $info['avdataoffset'] + round($current_segment * (($info['avdataend'] - $info['avdataoffset']) / $max_scan_segments))); if ($current_segment > 0) { $this->fseek($scan_start_offset[$current_segment]); $buffer_4k = $this->fread(4096); for ($j = 0; $j < (strlen($buffer_4k) - 4); $j++) { if (($buffer_4k[$j] == "\xFF") && ($buffer_4k[($j + 1)] > "\xE0")) { // synch detected if ($this->decodeMPEGaudioHeader($scan_start_offset[$current_segment] + $j, $dummy, false, false, $FastMode)) { $calculated_next_offset = $scan_start_offset[$current_segment] + $j + $dummy['mpeg']['audio']['framelength']; if ($this->decodeMPEGaudioHeader($calculated_next_offset, $dummy, false, false, $FastMode)) { $scan_start_offset[$current_segment] += $j; break; } } } } } $synchstartoffset = $scan_start_offset[$current_segment]; while (($synchstartoffset < $info['avdataend']) && $this->decodeMPEGaudioHeader($synchstartoffset, $dummy, false, false, $FastMode)) { $FastMode = true; $thisframebitrate = $MPEGaudioBitrateLookup[$MPEGaudioVersionLookup[$dummy['mpeg']['audio']['raw']['version']]][$MPEGaudioLayerLookup[$dummy['mpeg']['audio']['raw']['layer']]][$dummy['mpeg']['audio']['raw']['bitrate']]; if (empty($dummy['mpeg']['audio']['framelength'])) { $SynchErrorsFound++; $synchstartoffset++; } else { getid3_lib::safe_inc($info['mpeg']['audio']['bitrate_distribution'][$thisframebitrate]); getid3_lib::safe_inc($info['mpeg']['audio']['stereo_distribution'][$dummy['mpeg']['audio']['channelmode']]); getid3_lib::safe_inc($info['mpeg']['audio']['version_distribution'][$dummy['mpeg']['audio']['version']]); $synchstartoffset += $dummy['mpeg']['audio']['framelength']; } $frames_scanned++; if ($frames_scan_per_segment && (++$frames_scanned_this_segment >= $frames_scan_per_segment)) { $this_pct_scanned = getid3_lib::SafeDiv($this->ftell() - $scan_start_offset[$current_segment], $info['avdataend'] - $info['avdataoffset']); if (($current_segment == 0) && (($this_pct_scanned * $max_scan_segments) >= 1)) { // file likely contains < $max_frames_scan, just scan as one segment $max_scan_segments = 1; $frames_scan_per_segment = $max_frames_scan; } else { $pct_data_scanned += $this_pct_scanned; break; } } } } if ($pct_data_scanned > 0) { $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.'); foreach ($info['mpeg']['audio'] as $key1 => $value1) { if (!preg_match('#_distribution$#i', $key1)) { continue; } foreach ($value1 as $key2 => $value2) { $info['mpeg']['audio'][$key1][$key2] = round($value2 / $pct_data_scanned); } } } if ($SynchErrorsFound > 0) { $this->warning('Found '.$SynchErrorsFound.' synch errors in histogram analysis'); //return false; } $bittotal = 0; $framecounter = 0; foreach ($info['mpeg']['audio']['bitrate_distribution'] as $bitratevalue => $bitratecount) { $framecounter += $bitratecount; if ($bitratevalue != 'free') { $bittotal += ($bitratevalue * $bitratecount); } } if ($framecounter == 0) { $this->error('Corrupt MP3 file: framecounter == zero'); return false; } $info['mpeg']['audio']['frame_count'] = getid3_lib::CastAsInt($framecounter); $info['mpeg']['audio']['bitrate'] = ($bittotal / $framecounter); $info['audio']['bitrate'] = $info['mpeg']['audio']['bitrate']; // 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; } break; } } $info['audio']['channels'] = $info['mpeg']['audio']['channels']; if ($info['audio']['channels'] < 1) { $this->error('Corrupt MP3 file: no channels'); return false; } $info['audio']['channelmode'] = $info['mpeg']['audio']['channelmode']; $info['audio']['sample_rate'] = $info['mpeg']['audio']['sample_rate']; return true; } /** * @return array */ public static function MPEGaudioVersionArray() { static $MPEGaudioVersion = array('2.5', false, '2', '1'); return $MPEGaudioVersion; } /** * @return array */ public static function MPEGaudioLayerArray() { static $MPEGaudioLayer = array(false, 3, 2, 1); return $MPEGaudioLayer; } /** * @return array */ public static function MPEGaudioBitrateArray() { static $MPEGaudioBitrate; if (empty($MPEGaudioBitrate)) { $MPEGaudioBitrate = array ( '1' => array (1 => array('free', 32000, 64000, 96000, 128000, 160000, 192000, 224000, 256000, 288000, 320000, 352000, 384000, 416000, 448000), 2 => array('free', 32000, 48000, 56000, 64000, 80000, 96000, 112000, 128000, 160000, 192000, 224000, 256000, 320000, 384000), 3 => array('free', 32000, 40000, 48000, 56000, 64000, 80000, 96000, 112000, 128000, 160000, 192000, 224000, 256000, 320000) ), '2' => array (1 => array('free', 32000, 48000, 56000, 64000, 80000, 96000, 112000, 128000, 144000, 160000, 176000, 192000, 224000, 256000), 2 => array('free', 8000, 16000, 24000, 32000, 40000, 48000, 56000, 64000, 80000, 96000, 112000, 128000, 144000, 160000), ) ); $MPEGaudioBitrate['2'][3] = $MPEGaudioBitrate['2'][2]; $MPEGaudioBitrate['2.5'] = $MPEGaudioBitrate['2']; } return $MPEGaudioBitrate; } /** * @return array */ public static function MPEGaudioFrequencyArray() { static $MPEGaudioFrequency; if (empty($MPEGaudioFrequency)) { $MPEGaudioFrequency = array ( '1' => array(44100, 48000, 32000), '2' => array(22050, 24000, 16000), '2.5' => array(11025, 12000, 8000) ); } return $MPEGaudioFrequency; } /** * @return array */ public static function MPEGaudioChannelModeArray() { static $MPEGaudioChannelMode = array('stereo', 'joint stereo', 'dual channel', 'mono'); return $MPEGaudioChannelMode; } /** * @return array */ public static function MPEGaudioModeExtensionArray() { static $MPEGaudioModeExtension; if (empty($MPEGaudioModeExtension)) { $MPEGaudioModeExtension = array ( 1 => array('4-31', '8-31', '12-31', '16-31'), 2 => array('4-31', '8-31', '12-31', '16-31'), 3 => array('', 'IS', 'MS', 'IS+MS') ); } return $MPEGaudioModeExtension; } /** * @return array */ public static function MPEGaudioEmphasisArray() { static $MPEGaudioEmphasis = array('none', '50/15ms', false, 'CCIT J.17'); return $MPEGaudioEmphasis; } /** * @param string $head4 * @param bool $allowBitrate15 * * @return bool */ public static function MPEGaudioHeaderBytesValid($head4, $allowBitrate15=false) { return self::MPEGaudioHeaderValid(self::MPEGaudioHeaderDecode($head4), false, $allowBitrate15); } /** * @param array $rawarray * @param bool $echoerrors * @param bool $allowBitrate15 * * @return bool */ public static function MPEGaudioHeaderValid($rawarray, $echoerrors=false, $allowBitrate15=false) { if (!isset($rawarray['synch']) || ($rawarray['synch'] & 0x0FFE) != 0x0FFE) { return false; } static $MPEGaudioVersionLookup; static $MPEGaudioLayerLookup; static $MPEGaudioBitrateLookup; static $MPEGaudioFrequencyLookup; static $MPEGaudioChannelModeLookup; static $MPEGaudioModeExtensionLookup; static $MPEGaudioEmphasisLookup; if (empty($MPEGaudioVersionLookup)) { $MPEGaudioVersionLookup = self::MPEGaudioVersionArray(); $MPEGaudioLayerLookup = self::MPEGaudioLayerArray(); $MPEGaudioBitrateLookup = self::MPEGaudioBitrateArray(); $MPEGaudioFrequencyLookup = self::MPEGaudioFrequencyArray(); $MPEGaudioChannelModeLookup = self::MPEGaudioChannelModeArray(); $MPEGaudioModeExtensionLookup = self::MPEGaudioModeExtensionArray(); $MPEGaudioEmphasisLookup = self::MPEGaudioEmphasisArray(); } 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 if (strlen($Header4Bytes) != 4) { return false; } $MPEGrawHeader = array(); $MPEGrawHeader['synch'] = (getid3_lib::BigEndian2Int(substr($Header4Bytes, 0, 2)) & 0xFFE0) >> 4; $MPEGrawHeader['version'] = (ord($Header4Bytes[1]) & 0x18) >> 3; // BB $MPEGrawHeader['layer'] = (ord($Header4Bytes[1]) & 0x06) >> 1; // CC $MPEGrawHeader['protection'] = (ord($Header4Bytes[1]) & 0x01); // D $MPEGrawHeader['bitrate'] = (ord($Header4Bytes[2]) & 0xF0) >> 4; // EEEE $MPEGrawHeader['sample_rate'] = (ord($Header4Bytes[2]) & 0x0C) >> 2; // FF $MPEGrawHeader['padding'] = (ord($Header4Bytes[2]) & 0x02) >> 1; // G $MPEGrawHeader['private'] = (ord($Header4Bytes[2]) & 0x01); // H $MPEGrawHeader['channelmode'] = (ord($Header4Bytes[3]) & 0xC0) >> 6; // II $MPEGrawHeader['modeextension'] = (ord($Header4Bytes[3]) & 0x30) >> 4; // JJ $MPEGrawHeader['copyright'] = (ord($Header4Bytes[3]) & 0x08) >> 3; // K $MPEGrawHeader['original'] = (ord($Header4Bytes[3]) & 0x04) >> 2; // L $MPEGrawHeader['emphasis'] = (ord($Header4Bytes[3]) & 0x03); // MM return $MPEGrawHeader; } /** * @param int|string $bitrate * @param string $version * @param string $layer * @param bool $padding * @param int $samplerate * * @return int|false */ public static function MPEGaudioFrameLength(&$bitrate, &$version, &$layer, $padding, &$samplerate) { static $AudioFrameLengthCache = array(); if (!isset($AudioFrameLengthCache[$bitrate][$version][$layer][$padding][$samplerate])) { $AudioFrameLengthCache[$bitrate][$version][$layer][$padding][$samplerate] = false; if ($bitrate != 'free') { if ($version == '1') { if ($layer == '1') { // For Layer I slot is 32 bits long $FrameLengthCoefficient = 48; $SlotLength = 4; } else { // Layer 2 / 3 // for Layer 2 and Layer 3 slot is 8 bits long. $FrameLengthCoefficient = 144; $SlotLength = 1; } } else { // MPEG-2 / MPEG-2.5 if ($layer == '1') { // For Layer I slot is 32 bits long $FrameLengthCoefficient = 24; $SlotLength = 4; } elseif ($layer == '2') { // for Layer 2 and Layer 3 slot is 8 bits long. $FrameLengthCoefficient = 144; $SlotLength = 1; } else { // layer 3 // for Layer 2 and Layer 3 slot is 8 bits long. $FrameLengthCoefficient = 72; $SlotLength = 1; } } // FrameLengthInBytes = ((Coefficient * BitRate) / SampleRate) + Padding if ($samplerate > 0) { $NewFramelength = ($FrameLengthCoefficient * $bitrate) / $samplerate; $NewFramelength = floor($NewFramelength / $SlotLength) * $SlotLength; // round to next-lower multiple of SlotLength (1 byte for Layer 2/3, 4 bytes for Layer I) if ($padding) { $NewFramelength += $SlotLength; } $AudioFrameLengthCache[$bitrate][$version][$layer][$padding][$samplerate] = (int) $NewFramelength; } } } return $AudioFrameLengthCache[$bitrate][$version][$layer][$padding][$samplerate]; } /** * @param float|int $bit_rate * * @return int|float|string */ public static function ClosestStandardMP3Bitrate($bit_rate) { static $standard_bit_rates = array (320000, 256000, 224000, 192000, 160000, 128000, 112000, 96000, 80000, 64000, 56000, 48000, 40000, 32000, 24000, 16000, 8000); static $bit_rate_table = array (0=>'-'); $round_bit_rate = intval(round($bit_rate, -3)); if (!isset($bit_rate_table[$round_bit_rate])) { if ($round_bit_rate > max($standard_bit_rates)) { $bit_rate_table[$round_bit_rate] = round($bit_rate, 2 - strlen($bit_rate)); } else { $bit_rate_table[$round_bit_rate] = max($standard_bit_rates); foreach ($standard_bit_rates as $standard_bit_rate) { if ($round_bit_rate >= $standard_bit_rate + (($bit_rate_table[$round_bit_rate] - $standard_bit_rate) / 2)) { break; } $bit_rate_table[$round_bit_rate] = $standard_bit_rate; } } } return $bit_rate_table[$round_bit_rate]; } /** * @param string $version * @param string $channelmode * * @return int */ public static function XingVBRidOffset($version, $channelmode) { static $XingVBRidOffsetCache = array(); if (empty($XingVBRidOffsetCache)) { $XingVBRidOffsetCache = array ( '1' => array ('mono' => 0x15, // 4 + 17 = 21 'stereo' => 0x24, // 4 + 32 = 36 'joint stereo' => 0x24, 'dual channel' => 0x24 ), '2' => array ('mono' => 0x0D, // 4 + 9 = 13 'stereo' => 0x15, // 4 + 17 = 21 'joint stereo' => 0x15, 'dual channel' => 0x15 ), '2.5' => array ('mono' => 0x15, 'stereo' => 0x15, 'joint stereo' => 0x15, 'dual channel' => 0x15 ) ); } return $XingVBRidOffsetCache[$version][$channelmode]; } /** * @param int $VBRmethodID * * @return string */ public static function LAMEvbrMethodLookup($VBRmethodID) { static $LAMEvbrMethodLookup = array( 0x00 => 'unknown', 0x01 => 'cbr', 0x02 => 'abr', 0x03 => 'vbr-old / vbr-rh', 0x04 => 'vbr-new / vbr-mtrh', 0x05 => 'vbr-mt', 0x06 => 'vbr (full vbr method 4)', 0x08 => 'cbr (constant bitrate 2 pass)', 0x09 => 'abr (2 pass)', 0x0F => 'reserved' ); return (isset($LAMEvbrMethodLookup[$VBRmethodID]) ? $LAMEvbrMethodLookup[$VBRmethodID] : ''); } /** * @param int $StereoModeID * * @return string */ public static function LAMEmiscStereoModeLookup($StereoModeID) { static $LAMEmiscStereoModeLookup = array( 0 => 'mono', 1 => 'stereo', 2 => 'dual mono', 3 => 'joint stereo', 4 => 'forced stereo', 5 => 'auto', 6 => 'intensity stereo', 7 => 'other' ); return (isset($LAMEmiscStereoModeLookup[$StereoModeID]) ? $LAMEmiscStereoModeLookup[$StereoModeID] : ''); } /** * @param int $SourceSampleFrequencyID * * @return string */ public static function LAMEmiscSourceSampleFrequencyLookup($SourceSampleFrequencyID) { static $LAMEmiscSourceSampleFrequencyLookup = array( 0 => '<= 32 kHz', 1 => '44.1 kHz', 2 => '48 kHz', 3 => '> 48kHz' ); return (isset($LAMEmiscSourceSampleFrequencyLookup[$SourceSampleFrequencyID]) ? $LAMEmiscSourceSampleFrequencyLookup[$SourceSampleFrequencyID] : ''); } /** * @param int $SurroundInfoID * * @return string */ public static function LAMEsurroundInfoLookup($SurroundInfoID) { static $LAMEsurroundInfoLookup = array( 0 => 'no surround info', 1 => 'DPL encoding', 2 => 'DPL2 encoding', 3 => 'Ambisonic encoding' ); return (isset($LAMEsurroundInfoLookup[$SurroundInfoID]) ? $LAMEsurroundInfoLookup[$SurroundInfoID] : 'reserved'); } /** * @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'; // LAME 3.94 additions/changes $LAMEpresetUsedLookup[1010] = '--preset portable'; // 3.94a15 Oct 21 2003 $LAMEpresetUsedLookup[1015] = '--preset radio'; // 3.94a15 Oct 21 2003 $LAMEpresetUsedLookup[320] = '--preset insane'; // 3.94a15 Nov 12 2003 $LAMEpresetUsedLookup[410] = '-V9'; $LAMEpresetUsedLookup[420] = '-V8'; $LAMEpresetUsedLookup[440] = '-V6'; $LAMEpresetUsedLookup[430] = '--preset radio'; // 3.94a15 Nov 12 2003 $LAMEpresetUsedLookup[450] = '--preset '.(($LAMEtag['raw']['vbr_method'] == 4) ? 'fast ' : '').'portable'; // 3.94a15 Nov 12 2003 $LAMEpresetUsedLookup[460] = '--preset '.(($LAMEtag['raw']['vbr_method'] == 4) ? 'fast ' : '').'medium'; // 3.94a15 Nov 12 2003 $LAMEpresetUsedLookup[470] = '--r3mix'; // 3.94b1 Dec 18 2003 $LAMEpresetUsedLookup[480] = '--preset '.(($LAMEtag['raw']['vbr_method'] == 4) ? 'fast ' : '').'standard'; // 3.94a15 Nov 12 2003 $LAMEpresetUsedLookup[490] = '-V1'; $LAMEpresetUsedLookup[500] = '--preset '.(($LAMEtag['raw']['vbr_method'] == 4) ? 'fast ' : '').'extreme'; // 3.94a15 Nov 12 2003 return (isset($LAMEpresetUsedLookup[$LAMEtag['preset_used_id']]) ? $LAMEpresetUsedLookup[$LAMEtag['preset_used_id']] : 'new/unknown preset: '.$LAMEtag['preset_used_id'].' - report to info@getid3.org'); } } readme.txt 0000644 00000063332 15054343026 0006553 0 ustar 00 ///////////////////////////////////////////////////////////////// /// getID3() by James Heinrich <info@getid3.org> // // available at http://getid3.sourceforge.net // // or https://www.getid3.org // // also https://github.com/JamesHeinrich/getID3 // ///////////////////////////////////////////////////////////////// ***************************************************************** ***************************************************************** getID3() is released under multiple licenses. You may choose from the following licenses, and use getID3 according to the terms of the license most suitable to your project. GNU GPL: https://gnu.org/licenses/gpl.html (v3) https://gnu.org/licenses/old-licenses/gpl-2.0.html (v2) https://gnu.org/licenses/old-licenses/gpl-1.0.html (v1) GNU LGPL: https://gnu.org/licenses/lgpl.html (v3) Mozilla MPL: https://www.mozilla.org/MPL/2.0/ (v2) getID3 Commercial License: https://www.getid3.org/#gCL (no longer available, existing licenses remain valid) ***************************************************************** ***************************************************************** Copies of each of the above licenses are included in the 'licenses' directory of the getID3 distribution. +----------------------------------------------+ | If you want to donate, there is a link on | | https://www.getid3.org for PayPal donations. | +----------------------------------------------+ Quick Start =========================================================================== Q: How can I check that getID3() works on my server/files? A: Unzip getID3() to a directory, then access /demos/demo.browse.php Support =========================================================================== Q: I have a question, or I found a bug. What do I do? A: The preferred method of support requests and/or bug reports is the forum at http://support.getid3.org/ Sourceforge Notification =========================================================================== It's highly recommended that you sign up for notification from Sourceforge for when new versions are released. Please visit: http://sourceforge.net/project/showfiles.php?group_id=55859 and click the little "monitor package" icon/link. If you're previously signed up for the mailing list, be aware that it has been discontinued, only the automated Sourceforge notification will be used from now on. What does getID3() do? =========================================================================== Reads & parses (to varying degrees): ¤ tags: * APE (v1 and v2) * ID3v1 (& ID3v1.1) * ID3v2 (v2.4, v2.3, v2.2) * Lyrics3 (v1 & v2) ¤ audio-lossy: * MP3/MP2/MP1 * MPC / Musepack * Ogg (Vorbis, OggFLAC, Speex, Opus) * AAC / MP4 * AC3 * DTS * RealAudio * Speex * DSS * VQF ¤ audio-lossless: * AIFF * AU * Bonk * CD-audio (*.cda) * FLAC * LA (Lossless Audio) * LiteWave * LPAC * MIDI * Monkey's Audio * OptimFROG * RKAU * Shorten * TTA * VOC * WAV (RIFF) * WavPack ¤ audio-video: * ASF: ASF, Windows Media Audio (WMA), Windows Media Video (WMV) * AVI (RIFF) * Flash * Matroska (MKV) * MPEG-1 / MPEG-2 * NSV (Nullsoft Streaming Video) * Quicktime (including MP4) * RealVideo ¤ still image: * BMP * GIF * JPEG * PNG * TIFF * SWF (Flash) * PhotoCD ¤ data: * ISO-9660 CD-ROM image (directory structure) * SZIP (limited support) * ZIP (directory structure) * TAR * CUE Writes: * ID3v1 (& ID3v1.1) * ID3v2 (v2.3 & v2.4) * VorbisComment on OggVorbis * VorbisComment on FLAC (not OggFLAC) * APE v2 * Lyrics3 (delete only) Requirements =========================================================================== * PHP 4.2.0 up to 5.2.x for getID3() 1.7.x (and earlier) * PHP 5.0.5 (or higher) for getID3() 1.8.x (and up) * PHP 5.3.0 (or higher) for getID3() 1.9.17 (and up) * PHP 5.3.0 (or higher) for getID3() 2.0.x (and up) * at least 4MB memory for PHP. 8MB or more is highly recommended. 12MB is required with all modules loaded. Usage =========================================================================== See /demos/demo.basic.php for a very basic use of getID3() with no fancy output, just scanning one file. See structure.txt for the returned data structure. *> For an example of a complete directory-browsing, <* *> file-scanning implementation of getID3(), please run <* *> /demos/demo.browse.php <* See /demos/demo.mysql.php for a sample recursive scanning code that scans every file in a given directory, and all sub-directories, stores the results in a database and allows various analysis / maintenance operations To analyze remote files over HTTP or FTP you need to copy the file locally first before running getID3(). Your code would look something like this: // Copy remote file locally to scan with getID3() $remotefilename = 'http://www.example.com/filename.mp3'; if ($fp_remote = fopen($remotefilename, 'rb')) { $localtempfilename = tempnam('/tmp', 'getID3'); if ($fp_local = fopen($localtempfilename, 'wb')) { while ($buffer = fread($fp_remote, 32768)) { fwrite($fp_local, $buffer); } fclose($fp_local); $remote_headers = array_change_key_case(get_headers($remotefilename, 1), CASE_LOWER); $remote_filesize = (isset($remote_headers['content-length']) ? (is_array($remote_headers['content-length']) ? $remote_headers['content-length'][count($remote_headers['content-length']) - 1] : $remote_headers['content-length']) : null); // Initialize getID3 engine $getID3 = new getID3; $ThisFileInfo = $getID3->analyze($localtempfilename, $remote_filesize, basename($remotefilename)); // Delete temporary file unlink($localtempfilename); } fclose($fp_remote); } Note: since v1.9.9-20150212 it is possible a second and third parameter to $getID3->analyze(), for original filesize and original filename respectively. This permits you to download only a portion of a large remote file but get accurate playtime estimates, assuming the format only requires the beginning of the file for correct format analysis. See /demos/demo.write.php for how to write tags. What does the returned data structure look like? =========================================================================== See structure.txt It is recommended that you look at the output of /demos/demo.browse.php scanning the file(s) you're interested in to confirm what data is actually returned for any particular filetype in general, and your files in particular, as the actual data returned may vary considerably depending on what information is available in the file itself. Notes =========================================================================== getID3() 1.x: If the format parser encounters a critical problem, it will return something in $fileinfo['error'], describing the encountered error. If a less critical error or notice is generated it will appear in $fileinfo['warning']. Both keys may contain more than one warning or error. If something is returned in ['error'] then the file was not correctly parsed and returned data may or may not be correct and/or complete. If something is returned in ['warning'] (and not ['error']) then the data that is returned is OK - usually getID3() is reporting errors in the file that have been worked around due to known bugs in other programs. Some warnings may indicate that the data that is returned is OK but that some data could not be extracted due to errors in the file. getID3() 2.x: See above except errors are thrown (so you will only get one error). Disclaimer =========================================================================== getID3() has been tested on many systems, on many types of files, under many operating systems, and is generally believe to be stable and safe. That being said, there is still the chance there is an undiscovered and/or unfixed bug that may potentially corrupt your file, especially within the writing functions. By using getID3() you agree that it's not my fault if any of your files are corrupted. In fact, I'm not liable for anything :) License =========================================================================== GNU General Public License - see license.txt This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to: Free Software Foundation, Inc. 59 Temple Place - Suite 330 Boston, MA 02111-1307, USA. FAQ: Q: Can I use getID3() in my program? Do I need a commercial license? A: You're generally free to use getID3 however you see fit. The only case in which you would require a commercial license is if you're selling your closed-source program that integrates getID3. If you sell your program including a copy of getID3, that's fine as long as you include a copy of the sourcecode when you sell it. Or you can distribute your code without getID3 and say "download it from getid3.sourceforge.net" Why is it called "getID3()" if it does so much more than just that? =========================================================================== v0.1 did in fact just do that. I don't have a copy of code that old, but I could essentially write it today with a one-line function: function getID3($filename) { return unpack('a3TAG/a30title/a30artist/a30album/a4year/a28comment/c1track/c1genreid', substr(file_get_contents($filename), -128)); } Future Plans =========================================================================== https://www.getid3.org/phpBB3/viewforum.php?f=7 * Better support for MP4 container format * Scan for appended ID3v2 tag at end of file per ID3v2.4 specs (Section 5.0) * Support for JPEG-2000 (http://www.morgan-multimedia.com/jpeg2000_overview.htm) * Support for MOD (mod/stm/s3m/it/xm/mtm/ult/669) * Support for ACE (thanks Vince) * Support for Ogg other than Vorbis, Speex and OggFlac (ie. Ogg+Xvid) * Ability to create Xing/LAME VBR header for VBR MP3s that are missing VBR header * Ability to "clean" ID3v2 padding (replace invalid padding with valid padding) * Warn if MP3s change version mid-stream (in full-scan mode) * check for corrupt/broken mid-file MP3 streams in histogram scan * Support for lossless-compression formats (http://www.firstpr.com.au/audiocomp/lossless/#Links) (http://compression.ca/act-sound.html) (http://web.inter.nl.net/users/hvdh/lossless/lossless.htm) * Support for RIFF-INFO chunks * http://lotto.st-andrews.ac.uk/~njh/tag_interchange.html (thanks Nick Humfrey <njhØsurgeradio*co*uk>) * http://abcavi.narod.ru/sof/abcavi/infotags.htm (thanks Kibi) * Better support for Bink video * http://www.hr/josip/DSP/AudioFile2.html * http://www.pcisys.net/~melanson/codecs/ * Detect mp3PRO * Support for PSD * Support for JPC * Support for JP2 * Support for JPX * Support for JB2 * Support for IFF * Support for ICO * Support for ANI * Support for EXE (comments, author, etc) (thanks p*quaedackersØplanet*nl) * Support for DVD-IFO (region, subtitles, aspect ratio, etc) (thanks p*quaedackersØplanet*nl) * More complete support for SWF - parsing encapsulated MP3 and/or JPEG content (thanks n8n8Øyahoo*com) * Support for a2b * Optional scan-through-frames for AVI verification (thanks rockcohenØmassive-interactive*nl) * Support for TTF (thanks infoØbutterflyx*com) * Support for DSS (https://www.getid3.org/phpBB3/viewtopic.php?t=171) * Support for SMAF (http://smaf-yamaha.com/what/demo.html) https://www.getid3.org/phpBB3/viewtopic.php?t=182 * Support for AMR (https://www.getid3.org/phpBB3/viewtopic.php?t=195) * Support for 3gpp (https://www.getid3.org/phpBB3/viewtopic.php?t=195) * Support for ID4 (http://www.wackysoft.cjb.net grizlyY2KØhotmail*com) * Parse XML data returned in Ogg comments * Parse XML data from Quicktime SMIL metafiles (klausrathØmac*com) * ID3v2 genre string creator function * More complete parsing of JPG * Support for all old-style ASF packets * ASF/WMA/WMV tag writing * Parse declared T??? ID3v2 text information frames, where appropriate (thanks Christian Fritz for the idea) * Recognize encoder: http://www.guerillasoft.com/EncSpot2/index.html http://ff123.net/identify.html http://www.hydrogenaudio.org/?act=ST&f=16&t=9414 http://www.hydrogenaudio.org/?showtopic=11785 * Support for other OS/2 bitmap structures: Bitmap Array('BA'), Color Icon('CI'), Color Pointer('CP'), Icon('IC'), Pointer ('PT') http://netghost.narod.ru/gff/graphics/summary/os2bmp.htm * Support for WavPack RAW mode * ASF/WMA/WMV data packet parsing * ID3v2FrameFlagsLookupTagAlter() * ID3v2FrameFlagsLookupFileAlter() * obey ID3v2 tag alter/preserve/discard rules * http://www.geocities.com/SiliconValley/Sector/9654/Softdoc/Illyrium/Aolyr.htm * proper checking for LINK/LNK frame validity in ID3v2 writing * proper checking for ASPI-TLEN frame validity in ID3v2 writing * proper checking for COMR frame validity in ID3v2 writing * http://www.geocities.co.jp/SiliconValley-Oakland/3664/index.html * decode GEOB ID3v2 structure as encoded by RealJukebox, decode NCON ID3v2 structure as encoded by MusicMatch (probably won't happen - the formats are proprietary) Known Bugs/Issues in getID3() that may be fixed eventually =========================================================================== https://www.getid3.org/phpBB3/viewtopic.php?t=25 * Cannot determine bitrate for MPEG video with VBR video data (need documentation) * Interlace/progressive cannot be determined for MPEG video (need documentation) * MIDI playtime is sometimes inaccurate * AAC-RAW mode files cannot be identified * WavPack-RAW mode files cannot be identified * mp4 files report lots of "Unknown QuickTime atom type" (need documentation) * Encrypted ASF/WMA/WMV files warn about "unhandled GUID ASF_Content_Encryption_Object" * Bitrate split between audio and video cannot be calculated for NSV, only the total bitrate. (need documentation) * All Ogg formats (Vorbis, OggFLAC, Speex) are affected by the problem of large VorbisComments spanning multiple Ogg pages, but but only OggVorbis files can be processed with vorbiscomment. * The version of "head" supplied with Mac OS 10.2.8 (maybe other versions too) does only understands a single option (-n) and therefore fails. getID3 ignores this and returns wrong md5_data. Known Bugs/Issues in getID3() that cannot be fixed -------------------------------------------------- https://www.getid3.org/phpBB3/viewtopic.php?t=25 * 32-bit PHP installations only: Files larger than 2GB cannot always be parsed fully by getID3() due to limitations in the 32-bit PHP filesystem functions. NOTE: Since v1.7.8b3 there is partial support for larger-than- 2GB files, most of which will parse OK, as long as no critical data is located beyond the 2GB offset. Known will-work: * all file formats on 64-bit PHP * ZIP (format doesn't support files >2GB) * FLAC (current encoders don't support files >2GB) Known will-not-work: * ID3v1 tags (always located at end-of-file) * Lyrics3 tags (always located at end-of-file) * APE tags (always located at end-of-file) Maybe-will-work: * Quicktime (will work if needed metadata is before 2GB offset, that is if the file has been hinted/optimized for streaming) * RIFF.WAV (should work fine, but gives warnings about not being able to parse all chunks) * RIFF.AVI (playtime will probably be wrong, is only based on "movi" chunk that fits in the first 2GB, should issue error to show that playtime is incorrect. Other data should be mostly correct, assuming that data is constant throughout the file) * PHP <= v5 on Windows cannot read UTF-8 filenames Known Bugs/Issues in other programs ----------------------------------- https://www.getid3.org/phpBB3/viewtopic.php?t=25 * MusicBrainz Picard (at least up to v1.3.2) writes multiple ID3v2.3 genres in non-standard forward-slash separated text rather than parenthesis-numeric+refinement style per the ID3v2.3 specs. Tags written in ID3v2.4 mode are written correctly. (detected and worked around by getID3()) * PZ TagEditor v4.53.408 has been known to insert ID3v2.3 frames into an existing ID3v2.2 tag which, of course, breaks things * Windows Media Player (up to v11) and iTunes (up to v10+) do not correctly handle ID3v2.3 tags with UTF-16BE+BOM encoding (they assume the data is UTF-16LE+BOM and either crash (WMP) or output Asian character set (iTunes) * Winamp (up to v2.80 at least) does not support ID3v2.4 tags, only ID3v2.3 see: http://forums.winamp.com/showthread.php?postid=387524 * Some versions of Helium2 (www.helium2.com) do not write ID3v2.4-compliant Frame Sizes, even though the tag is marked as ID3v2.4) (detected by getID3()) * MP3ext V3.3.17 places a non-compliant padding string at the end of the ID3v2 header. This is supposedly fixed in v3.4b21 but only if you manually add a registry key. This fix is not yet confirmed. (detected by getID3()) * CDex v1.40 (fixed by v1.50b7) writes non-compliant Ogg comment strings, supposed to be in the format "NAME=value" but actually written just "value" (detected by getID3()) * Oggenc 0.9-rc3 flags the encoded file as ABR whether it's actually ABR or VBR. * iTunes (versions "v7.0.0.70" is known-guilty, probably other versions are too) writes ID3v2.3 comment tags using an ID3v2.2 frame name (3-bytes) null-padded to 4 bytes which is not valid for ID3v2.3+ (detected by getID3() since 1.9.12-201603221746) * iTunes (versions "X v2.0.3", "v3.0.1" are known-guilty, probably other versions are too) writes ID3v2.3 comment tags using a frame name 'COM ' which is not valid for ID3v2.3+ (it's an ID3v2.2-style frame name) (detected by getID3()) * MP2enc does not encode mono CBR MP2 files properly (half speed sound and double playtime) * MP2enc does not encode mono VBR MP2 files properly (actually encoded as stereo) * tooLAME does not encode mono VBR MP2 files properly (actually encoded as stereo) * AACenc encodes files in VBR mode (actually ABR) even if CBR is specified * AAC/ADIF - bitrate_mode = cbr for vbr files * LAME 3.90-3.92 prepends one frame of null data (space for the LAME/VBR header, but it never gets written) when encoding in CBR mode with the DLL * Ahead Nero encodes TwinVQF with a DSIZ value (which is supposed to be the filesize in bytes) of "0" for TwinVQF v1.0 and "1" for TwinVQF v2.0 (detected by getID3()) * Ahead Nero encodes TwinVQF files 1 second shorter than they should be * AAC-ADTS files are always actually encoded VBR, even if CBR mode is specified (the CBR-mode switches on the encoder enable ABR mode, not CBR as such, but it's not possible to tell the difference between such ABR files and true VBR) * STREAMINFO.audio_signature in OggFLAC is always null. "The reason it's like that is because there is no seeking support in libOggFLAC yet, so it has no way to go back and write the computed sum after encoding. Seeking support in Ogg FLAC is the #1 item for the next release." - Josh Coalson (FLAC developer) NOTE: getID3() will calculate md5_data in a method similar to other file formats, but that value cannot be compared to the md5_data value from FLAC data in a FLAC file format. * STREAMINFO.audio_signature is not calculated in FLAC v0.3.0 & v0.4.0 - getID3() will calculate md5_data in a method similar to other file formats, but that value cannot be compared to the md5_data value from FLAC v0.5.0+ * RioPort (various versions including 2.0 and 3.11) tags ID3v2 with a WCOM frame that has no data portion * Earlier versions of Coolplayer adds illegal ID3 tags to Ogg Vorbis files, thus making them corrupt. * Meracl ID3 Tag Writer v1.3.4 (and older) incorrectly truncates the last byte of data from an MP3 file when appending a new ID3v1 tag. (detected by getID3()) * Lossless-Audio files encoded with and without the -noseek switch do actually differ internally and therefore cannot match md5_data * iTunes has been known to append a new ID3v1 tag on the end of an existing ID3v1 tag when ID3v2 tag is also present (detected by getID3()) * MediaMonkey may write a blank RGAD ID3v2 frame but put actual replay gain adjustments in a series of user-defined TXXX frames (detected and handled by getID3() since v1.9.2) Reference material: =========================================================================== [www.id3.org material now mirrored at http://id3lib.sourceforge.net/id3/] * http://www.id3.org/id3v2.4.0-structure.txt * http://www.id3.org/id3v2.4.0-frames.txt * http://www.id3.org/id3v2.4.0-changes.txt * http://www.id3.org/id3v2.3.0.txt * http://www.id3.org/id3v2-00.txt * http://www.id3.org/mp3frame.html * http://minnie.tuhs.org/pipermail/mp3encoder/2001-January/001800.html <mathewhendry@hotmail.com> * http://www.dv.co.yu/mpgscript/mpeghdr.htm * http://www.mp3-tech.org/programmer/frame_header.html * http://users.belgacom.net/gc247244/extra/tag.html * http://gabriel.mp3-tech.org/mp3infotag.html * http://www.id3.org/iso4217.html * http://www.unicode.org/Public/MAPPINGS/ISO8859/8859-1.TXT * http://www.xiph.org/ogg/vorbis/doc/framing.html * http://www.xiph.org/ogg/vorbis/doc/v-comment.html * http://leknor.com/code/php/class.ogg.php.txt * http://www.id3.org/iso639-2.html * http://www.id3.org/lyrics3.html * http://www.id3.org/lyrics3200.html * http://www.psc.edu/general/software/packages/ieee/ieee.html * http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/ieee-expl.html * http://www.scri.fsu.edu/~jac/MAD3401/Backgrnd/binary.html * http://www.jmcgowan.com/avi.html * http://www.wotsit.org/ * http://www.herdsoft.com/ti/davincie/davp3xo2.htm * http://www.mathdogs.com/vorbis-illuminated/bitstream-appendix.html * "Standard MIDI File Format" by Dustin Caldwell (from www.wotsit.org) * http://midistudio.com/Help/GMSpecs_Patches.htm * http://www.xiph.org/archives/vorbis/200109/0459.html * http://www.replaygain.org/ * http://www.lossless-audio.com/ * http://download.microsoft.com/download/winmediatech40/Doc/1.0/WIN98MeXP/EN-US/ASF_Specification_v.1.0.exe * http://mediaxw.sourceforge.net/files/doc/Active%20Streaming%20Format%20(ASF)%201.0%20Specification.pdf * http://www.uni-jena.de/~pfk/mpp/sv8/ (archived at http://www.hydrogenaudio.org/musepack/klemm/www.personal.uni-jena.de/~pfk/mpp/sv8/) * http://jfaul.de/atl/ * http://www.uni-jena.de/~pfk/mpp/ (archived at http://www.hydrogenaudio.org/musepack/klemm/www.personal.uni-jena.de/~pfk/mpp/) * http://www.libpng.org/pub/png/spec/png-1.2-pdg.html * http://www.real.com/devzone/library/creating/rmsdk/doc/rmff.htm * http://www.fastgraph.com/help/bmp_os2_header_format.html * http://netghost.narod.ru/gff/graphics/summary/os2bmp.htm * http://flac.sourceforge.net/format.html * http://www.research.att.com/projects/mpegaudio/mpeg2.html * http://www.audiocoding.com/wiki/index.php?page=AAC * http://libmpeg.org/mpeg4/doc/w2203tfs.pdf * http://www.geocities.com/xhelmboyx/quicktime/formats/qtm-layout.txt * http://developer.apple.com/techpubs/quicktime/qtdevdocs/RM/frameset.htm * http://www.nullsoft.com/nsv/ * http://www.wotsit.org/download.asp?f=iso9660 * http://sandbox.mc.edu/~bennet/cs110/tc/tctod.html * http://www.cdroller.com/htm/readdata.html * http://www.speex.org/manual/node10.html * http://www.harmony-central.com/Computer/Programming/aiff-file-format.doc * http://www.faqs.org/rfcs/rfc2361.html * http://ghido.shelter.ro/ * http://www.ebu.ch/tech_t3285.pdf * http://www.sr.se/utveckling/tu/bwf * http://ftp.aessc.org/pub/aes46-2002.pdf * http://cartchunk.org:8080/ * http://www.broadcastpapers.com/radio/cartchunk01.htm * http://www.hr/josip/DSP/AudioFile2.html * http://home.attbi.com/~chris.bagwell/AudioFormats-11.html * http://www.pure-mac.com/extkey.html * http://cesnet.dl.sourceforge.net/sourceforge/bonkenc/bonk-binary-format-0.9.txt * http://www.headbands.com/gspot/ * http://www.openswf.org/spec/SWFfileformat.html * http://j-faul.virtualave.net/ * http://www.btinternet.com/~AnthonyJ/Atari/programming/avr_format.html * http://cui.unige.ch/OSG/info/AudioFormats/ap11.html * http://sswf.sourceforge.net/SWFalexref.html * http://www.geocities.com/xhelmboyx/quicktime/formats/qti-layout.txt * http://www-lehre.informatik.uni-osnabrueck.de/~fbstark/diplom/docs/swf/Flash_Uncovered.htm * http://developer.apple.com/quicktime/icefloe/dispatch012.html * http://www.csdn.net/Dev/Format/graphics/PCD.htm * http://tta.iszf.irk.ru/ * http://www.atsc.org/standards/a_52a.pdf * http://www.alanwood.net/unicode/ * http://www.freelists.org/archives/matroska-devel/07-2003/msg00010.html * http://www.its.msstate.edu/net/real/reports/config/tags.stats * http://homepages.slingshot.co.nz/~helmboy/quicktime/formats/qtm-layout.txt * http://brennan.young.net/Comp/LiveStage/things.html * http://www.multiweb.cz/twoinches/MP3inside.htm * http://www.geocities.co.jp/SiliconValley-Oakland/3664/alittle.html#GenreExtended * http://www.mactech.com/articles/mactech/Vol.06/06.01/SANENormalized/ * http://www.unicode.org/unicode/faq/utf_bom.html * http://tta.corecodec.org/?menu=format * http://www.scvi.net/nsvformat.htm * http://pda.etsi.org/pda/queryform.asp * http://cpansearch.perl.org/src/RGIBSON/Audio-DSS-0.02/lib/Audio/DSS.pm * http://trac.musepack.net/trac/wiki/SV8Specification * http://wyday.com/cuesharp/specification.php * http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/Nikon.html * http://www.codeproject.com/Articles/8295/MPEG-Audio-Frame-Header * http://dsd-guide.com/sites/default/files/white-papers/DSFFileFormatSpec_E.pdf * https://fileformats.fandom.com/wiki/Torrent_file module.audio-video.matroska.php 0000644 00000321213 15054343026 0012572 0 ustar 00 <?php ///////////////////////////////////////////////////////////////// /// 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-video.matriska.php // // module for analyzing Matroska containers // // dependencies: NONE // // /// ///////////////////////////////////////////////////////////////// if (!defined('GETID3_INCLUDEPATH')) { // prevent path-exposing attacks that access modules directly on public webservers exit; } define('EBML_ID_CHAPTERS', 0x0043A770); // [10][43][A7][70] -- A system to define basic menus and partition data. For more detailed information, look at the Chapters Explanation. define('EBML_ID_SEEKHEAD', 0x014D9B74); // [11][4D][9B][74] -- Contains the position of other level 1 elements. define('EBML_ID_TAGS', 0x0254C367); // [12][54][C3][67] -- Element containing elements specific to Tracks/Chapters. A list of valid tags can be found <http://www.matroska.org/technical/specs/tagging/index.html>. define('EBML_ID_INFO', 0x0549A966); // [15][49][A9][66] -- Contains miscellaneous general information and statistics on the file. define('EBML_ID_TRACKS', 0x0654AE6B); // [16][54][AE][6B] -- A top-level block of information with many tracks described. define('EBML_ID_SEGMENT', 0x08538067); // [18][53][80][67] -- This element contains all other top-level (level 1) elements. Typically a Matroska file is composed of 1 segment. define('EBML_ID_ATTACHMENTS', 0x0941A469); // [19][41][A4][69] -- Contain attached files. define('EBML_ID_EBML', 0x0A45DFA3); // [1A][45][DF][A3] -- Set the EBML characteristics of the data to follow. Each EBML document has to start with this. define('EBML_ID_CUES', 0x0C53BB6B); // [1C][53][BB][6B] -- A top-level element to speed seeking access. All entries are local to the segment. define('EBML_ID_CLUSTER', 0x0F43B675); // [1F][43][B6][75] -- The lower level element containing the (monolithic) Block structure. define('EBML_ID_LANGUAGE', 0x02B59C); // [22][B5][9C] -- Specifies the language of the track in the Matroska languages form. define('EBML_ID_TRACKTIMECODESCALE', 0x03314F); // [23][31][4F] -- The scale to apply on this track to work at normal speed in relation with other tracks (mostly used to adjust video speed when the audio length differs). define('EBML_ID_DEFAULTDURATION', 0x03E383); // [23][E3][83] -- Number of nanoseconds (i.e. not scaled) per frame. define('EBML_ID_CODECNAME', 0x058688); // [25][86][88] -- A human-readable string specifying the codec. define('EBML_ID_CODECDOWNLOADURL', 0x06B240); // [26][B2][40] -- A URL to download about the codec used. define('EBML_ID_TIMECODESCALE', 0x0AD7B1); // [2A][D7][B1] -- Timecode scale in nanoseconds (1.000.000 means all timecodes in the segment are expressed in milliseconds). define('EBML_ID_COLOURSPACE', 0x0EB524); // [2E][B5][24] -- Same value as in AVI (32 bits). define('EBML_ID_GAMMAVALUE', 0x0FB523); // [2F][B5][23] -- Gamma Value. define('EBML_ID_CODECSETTINGS', 0x1A9697); // [3A][96][97] -- A string describing the encoding setting used. define('EBML_ID_CODECINFOURL', 0x1B4040); // [3B][40][40] -- A URL to find information about the codec used. define('EBML_ID_PREVFILENAME', 0x1C83AB); // [3C][83][AB] -- An escaped filename corresponding to the previous segment. define('EBML_ID_PREVUID', 0x1CB923); // [3C][B9][23] -- A unique ID to identify the previous chained segment (128 bits). define('EBML_ID_NEXTFILENAME', 0x1E83BB); // [3E][83][BB] -- An escaped filename corresponding to the next segment. define('EBML_ID_NEXTUID', 0x1EB923); // [3E][B9][23] -- A unique ID to identify the next chained segment (128 bits). define('EBML_ID_CONTENTCOMPALGO', 0x0254); // [42][54] -- The compression algorithm used. Algorithms that have been specified so far are: define('EBML_ID_CONTENTCOMPSETTINGS', 0x0255); // [42][55] -- Settings that might be needed by the decompressor. For Header Stripping (ContentCompAlgo=3), the bytes that were removed from the beggining of each frames of the track. define('EBML_ID_DOCTYPE', 0x0282); // [42][82] -- A string that describes the type of document that follows this EBML header ('matroska' in our case). define('EBML_ID_DOCTYPEREADVERSION', 0x0285); // [42][85] -- The minimum DocType version an interpreter has to support to read this file. define('EBML_ID_EBMLVERSION', 0x0286); // [42][86] -- The version of EBML parser used to create the file. define('EBML_ID_DOCTYPEVERSION', 0x0287); // [42][87] -- The version of DocType interpreter used to create the file. define('EBML_ID_EBMLMAXIDLENGTH', 0x02F2); // [42][F2] -- The maximum length of the IDs you'll find in this file (4 or less in Matroska). define('EBML_ID_EBMLMAXSIZELENGTH', 0x02F3); // [42][F3] -- The maximum length of the sizes you'll find in this file (8 or less in Matroska). This does not override the element size indicated at the beginning of an element. Elements that have an indicated size which is larger than what is allowed by EBMLMaxSizeLength shall be considered invalid. define('EBML_ID_EBMLREADVERSION', 0x02F7); // [42][F7] -- The minimum EBML version a parser has to support to read this file. define('EBML_ID_CHAPLANGUAGE', 0x037C); // [43][7C] -- The languages corresponding to the string, in the bibliographic ISO-639-2 form. define('EBML_ID_CHAPCOUNTRY', 0x037E); // [43][7E] -- The countries corresponding to the string, same 2 octets as in Internet domains. define('EBML_ID_SEGMENTFAMILY', 0x0444); // [44][44] -- A randomly generated unique ID that all segments related to each other must use (128 bits). define('EBML_ID_DATEUTC', 0x0461); // [44][61] -- Date of the origin of timecode (value 0), i.e. production date. define('EBML_ID_TAGLANGUAGE', 0x047A); // [44][7A] -- Specifies the language of the tag specified, in the Matroska languages form. define('EBML_ID_TAGDEFAULT', 0x0484); // [44][84] -- Indication to know if this is the default/original language to use for the given tag. define('EBML_ID_TAGBINARY', 0x0485); // [44][85] -- The values of the Tag if it is binary. Note that this cannot be used in the same SimpleTag as TagString. define('EBML_ID_TAGSTRING', 0x0487); // [44][87] -- The value of the Tag. define('EBML_ID_DURATION', 0x0489); // [44][89] -- Duration of the segment (based on TimecodeScale). define('EBML_ID_CHAPPROCESSPRIVATE', 0x050D); // [45][0D] -- Some optional data attached to the ChapProcessCodecID information. For ChapProcessCodecID = 1, it is the "DVD level" equivalent. define('EBML_ID_CHAPTERFLAGENABLED', 0x0598); // [45][98] -- Specify wether the chapter is enabled. It can be enabled/disabled by a Control Track. When disabled, the movie should skip all the content between the TimeStart and TimeEnd of this chapter. define('EBML_ID_TAGNAME', 0x05A3); // [45][A3] -- The name of the Tag that is going to be stored. define('EBML_ID_EDITIONENTRY', 0x05B9); // [45][B9] -- Contains all information about a segment edition. define('EBML_ID_EDITIONUID', 0x05BC); // [45][BC] -- A unique ID to identify the edition. It's useful for tagging an edition. define('EBML_ID_EDITIONFLAGHIDDEN', 0x05BD); // [45][BD] -- If an edition is hidden (1), it should not be available to the user interface (but still to Control Tracks). define('EBML_ID_EDITIONFLAGDEFAULT', 0x05DB); // [45][DB] -- If a flag is set (1) the edition should be used as the default one. define('EBML_ID_EDITIONFLAGORDERED', 0x05DD); // [45][DD] -- Specify if the chapters can be defined multiple times and the order to play them is enforced. define('EBML_ID_FILEDATA', 0x065C); // [46][5C] -- The data of the file. define('EBML_ID_FILEMIMETYPE', 0x0660); // [46][60] -- MIME type of the file. define('EBML_ID_FILENAME', 0x066E); // [46][6E] -- Filename of the attached file. define('EBML_ID_FILEREFERRAL', 0x0675); // [46][75] -- A binary value that a track/codec can refer to when the attachment is needed. define('EBML_ID_FILEDESCRIPTION', 0x067E); // [46][7E] -- A human-friendly name for the attached file. define('EBML_ID_FILEUID', 0x06AE); // [46][AE] -- Unique ID representing the file, as random as possible. define('EBML_ID_CONTENTENCALGO', 0x07E1); // [47][E1] -- The encryption algorithm used. The value '0' means that the contents have not been encrypted but only signed. Predefined values: define('EBML_ID_CONTENTENCKEYID', 0x07E2); // [47][E2] -- For public key algorithms this is the ID of the public key the data was encrypted with. define('EBML_ID_CONTENTSIGNATURE', 0x07E3); // [47][E3] -- A cryptographic signature of the contents. define('EBML_ID_CONTENTSIGKEYID', 0x07E4); // [47][E4] -- This is the ID of the private key the data was signed with. define('EBML_ID_CONTENTSIGALGO', 0x07E5); // [47][E5] -- The algorithm used for the signature. A value of '0' means that the contents have not been signed but only encrypted. Predefined values: define('EBML_ID_CONTENTSIGHASHALGO', 0x07E6); // [47][E6] -- The hash algorithm used for the signature. A value of '0' means that the contents have not been signed but only encrypted. Predefined values: define('EBML_ID_MUXINGAPP', 0x0D80); // [4D][80] -- Muxing application or library ("libmatroska-0.4.3"). define('EBML_ID_SEEK', 0x0DBB); // [4D][BB] -- Contains a single seek entry to an EBML element. define('EBML_ID_CONTENTENCODINGORDER', 0x1031); // [50][31] -- Tells when this modification was used during encoding/muxing starting with 0 and counting upwards. The decoder/demuxer has to start with the highest order number it finds and work its way down. This value has to be unique over all ContentEncodingOrder elements in the segment. define('EBML_ID_CONTENTENCODINGSCOPE', 0x1032); // [50][32] -- A bit field that describes which elements have been modified in this way. Values (big endian) can be OR'ed. Possible values: define('EBML_ID_CONTENTENCODINGTYPE', 0x1033); // [50][33] -- A value describing what kind of transformation has been done. Possible values: define('EBML_ID_CONTENTCOMPRESSION', 0x1034); // [50][34] -- Settings describing the compression used. Must be present if the value of ContentEncodingType is 0 and absent otherwise. Each block must be decompressable even if no previous block is available in order not to prevent seeking. define('EBML_ID_CONTENTENCRYPTION', 0x1035); // [50][35] -- Settings describing the encryption used. Must be present if the value of ContentEncodingType is 1 and absent otherwise. define('EBML_ID_CUEREFNUMBER', 0x135F); // [53][5F] -- Number of the referenced Block of Track X in the specified Cluster. define('EBML_ID_NAME', 0x136E); // [53][6E] -- A human-readable track name. define('EBML_ID_CUEBLOCKNUMBER', 0x1378); // [53][78] -- Number of the Block in the specified Cluster. define('EBML_ID_TRACKOFFSET', 0x137F); // [53][7F] -- A value to add to the Block's Timecode. This can be used to adjust the playback offset of a track. define('EBML_ID_SEEKID', 0x13AB); // [53][AB] -- The binary ID corresponding to the element name. define('EBML_ID_SEEKPOSITION', 0x13AC); // [53][AC] -- The position of the element in the segment in octets (0 = first level 1 element). define('EBML_ID_STEREOMODE', 0x13B8); // [53][B8] -- Stereo-3D video mode. define('EBML_ID_OLDSTEREOMODE', 0x13B9); // [53][B9] -- Bogus StereoMode value used in old versions of libmatroska. DO NOT USE. (0: mono, 1: right eye, 2: left eye, 3: both eyes). define('EBML_ID_PIXELCROPBOTTOM', 0x14AA); // [54][AA] -- The number of video pixels to remove at the bottom of the image (for HDTV content). define('EBML_ID_DISPLAYWIDTH', 0x14B0); // [54][B0] -- Width of the video frames to display. define('EBML_ID_DISPLAYUNIT', 0x14B2); // [54][B2] -- Type of the unit for DisplayWidth/Height (0: pixels, 1: centimeters, 2: inches). define('EBML_ID_ASPECTRATIOTYPE', 0x14B3); // [54][B3] -- Specify the possible modifications to the aspect ratio (0: free resizing, 1: keep aspect ratio, 2: fixed). define('EBML_ID_DISPLAYHEIGHT', 0x14BA); // [54][BA] -- Height of the video frames to display. define('EBML_ID_PIXELCROPTOP', 0x14BB); // [54][BB] -- The number of video pixels to remove at the top of the image. define('EBML_ID_PIXELCROPLEFT', 0x14CC); // [54][CC] -- The number of video pixels to remove on the left of the image. define('EBML_ID_PIXELCROPRIGHT', 0x14DD); // [54][DD] -- The number of video pixels to remove on the right of the image. define('EBML_ID_FLAGFORCED', 0x15AA); // [55][AA] -- Set if that track MUST be used during playback. There can be many forced track for a kind (audio, video or subs), the player should select the one which language matches the user preference or the default + forced track. Overlay MAY happen between a forced and non-forced track of the same kind. define('EBML_ID_MAXBLOCKADDITIONID', 0x15EE); // [55][EE] -- The maximum value of BlockAddID. A value 0 means there is no BlockAdditions for this track. define('EBML_ID_WRITINGAPP', 0x1741); // [57][41] -- Writing application ("mkvmerge-0.3.3"). define('EBML_ID_CLUSTERSILENTTRACKS', 0x1854); // [58][54] -- The list of tracks that are not used in that part of the stream. It is useful when using overlay tracks on seeking. Then you should decide what track to use. define('EBML_ID_CLUSTERSILENTTRACKNUMBER', 0x18D7); // [58][D7] -- One of the track number that are not used from now on in the stream. It could change later if not specified as silent in a further Cluster. define('EBML_ID_ATTACHEDFILE', 0x21A7); // [61][A7] -- An attached file. define('EBML_ID_CONTENTENCODING', 0x2240); // [62][40] -- Settings for one content encoding like compression or encryption. define('EBML_ID_BITDEPTH', 0x2264); // [62][64] -- Bits per sample, mostly used for PCM. define('EBML_ID_CODECPRIVATE', 0x23A2); // [63][A2] -- Private data only known to the codec. define('EBML_ID_TARGETS', 0x23C0); // [63][C0] -- Contain all UIDs where the specified meta data apply. It is void to describe everything in the segment. define('EBML_ID_CHAPTERPHYSICALEQUIV', 0x23C3); // [63][C3] -- Specify the physical equivalent of this ChapterAtom like "DVD" (60) or "SIDE" (50), see complete list of values. define('EBML_ID_TAGCHAPTERUID', 0x23C4); // [63][C4] -- A unique ID to identify the Chapter(s) the tags belong to. If the value is 0 at this level, the tags apply to all chapters in the Segment. define('EBML_ID_TAGTRACKUID', 0x23C5); // [63][C5] -- A unique ID to identify the Track(s) the tags belong to. If the value is 0 at this level, the tags apply to all tracks in the Segment. define('EBML_ID_TAGATTACHMENTUID', 0x23C6); // [63][C6] -- A unique ID to identify the Attachment(s) the tags belong to. If the value is 0 at this level, the tags apply to all the attachments in the Segment. define('EBML_ID_TAGEDITIONUID', 0x23C9); // [63][C9] -- A unique ID to identify the EditionEntry(s) the tags belong to. If the value is 0 at this level, the tags apply to all editions in the Segment. define('EBML_ID_TARGETTYPE', 0x23CA); // [63][CA] -- An informational string that can be used to display the logical level of the target like "ALBUM", "TRACK", "MOVIE", "CHAPTER", etc (see TargetType). define('EBML_ID_TRACKTRANSLATE', 0x2624); // [66][24] -- The track identification for the given Chapter Codec. define('EBML_ID_TRACKTRANSLATETRACKID', 0x26A5); // [66][A5] -- The binary value used to represent this track in the chapter codec data. The format depends on the ChapProcessCodecID used. define('EBML_ID_TRACKTRANSLATECODEC', 0x26BF); // [66][BF] -- The chapter codec using this ID (0: Matroska Script, 1: DVD-menu). define('EBML_ID_TRACKTRANSLATEEDITIONUID', 0x26FC); // [66][FC] -- Specify an edition UID on which this translation applies. When not specified, it means for all editions found in the segment. define('EBML_ID_SIMPLETAG', 0x27C8); // [67][C8] -- Contains general information about the target. define('EBML_ID_TARGETTYPEVALUE', 0x28CA); // [68][CA] -- A number to indicate the logical level of the target (see TargetType). define('EBML_ID_CHAPPROCESSCOMMAND', 0x2911); // [69][11] -- Contains all the commands associated to the Atom. define('EBML_ID_CHAPPROCESSTIME', 0x2922); // [69][22] -- Defines when the process command should be handled (0: during the whole chapter, 1: before starting playback, 2: after playback of the chapter). define('EBML_ID_CHAPTERTRANSLATE', 0x2924); // [69][24] -- A tuple of corresponding ID used by chapter codecs to represent this segment. define('EBML_ID_CHAPPROCESSDATA', 0x2933); // [69][33] -- Contains the command information. The data should be interpreted depending on the ChapProcessCodecID value. For ChapProcessCodecID = 1, the data correspond to the binary DVD cell pre/post commands. define('EBML_ID_CHAPPROCESS', 0x2944); // [69][44] -- Contains all the commands associated to the Atom. define('EBML_ID_CHAPPROCESSCODECID', 0x2955); // [69][55] -- Contains the type of the codec used for the processing. A value of 0 means native Matroska processing (to be defined), a value of 1 means the DVD command set is used. More codec IDs can be added later. define('EBML_ID_CHAPTERTRANSLATEID', 0x29A5); // [69][A5] -- The binary value used to represent this segment in the chapter codec data. The format depends on the ChapProcessCodecID used. define('EBML_ID_CHAPTERTRANSLATECODEC', 0x29BF); // [69][BF] -- The chapter codec using this ID (0: Matroska Script, 1: DVD-menu). define('EBML_ID_CHAPTERTRANSLATEEDITIONUID', 0x29FC); // [69][FC] -- Specify an edition UID on which this correspondance applies. When not specified, it means for all editions found in the segment. define('EBML_ID_CONTENTENCODINGS', 0x2D80); // [6D][80] -- Settings for several content encoding mechanisms like compression or encryption. define('EBML_ID_MINCACHE', 0x2DE7); // [6D][E7] -- The minimum number of frames a player should be able to cache during playback. If set to 0, the reference pseudo-cache system is not used. define('EBML_ID_MAXCACHE', 0x2DF8); // [6D][F8] -- The maximum cache size required to store referenced frames in and the current frame. 0 means no cache is needed. define('EBML_ID_CHAPTERSEGMENTUID', 0x2E67); // [6E][67] -- A segment to play in place of this chapter. Edition ChapterSegmentEditionUID should be used for this segment, otherwise no edition is used. define('EBML_ID_CHAPTERSEGMENTEDITIONUID', 0x2EBC); // [6E][BC] -- The edition to play from the segment linked in ChapterSegmentUID. define('EBML_ID_TRACKOVERLAY', 0x2FAB); // [6F][AB] -- Specify that this track is an overlay track for the Track specified (in the u-integer). That means when this track has a gap (see SilentTracks) the overlay track should be used instead. The order of multiple TrackOverlay matters, the first one is the one that should be used. If not found it should be the second, etc. define('EBML_ID_TAG', 0x3373); // [73][73] -- Element containing elements specific to Tracks/Chapters. define('EBML_ID_SEGMENTFILENAME', 0x3384); // [73][84] -- A filename corresponding to this segment. define('EBML_ID_SEGMENTUID', 0x33A4); // [73][A4] -- A randomly generated unique ID to identify the current segment between many others (128 bits). define('EBML_ID_CHAPTERUID', 0x33C4); // [73][C4] -- A unique ID to identify the Chapter. define('EBML_ID_TRACKUID', 0x33C5); // [73][C5] -- A unique ID to identify the Track. This should be kept the same when making a direct stream copy of the Track to another file. define('EBML_ID_ATTACHMENTLINK', 0x3446); // [74][46] -- The UID of an attachment that is used by this codec. define('EBML_ID_CLUSTERBLOCKADDITIONS', 0x35A1); // [75][A1] -- Contain additional blocks to complete the main one. An EBML parser that has no knowledge of the Block structure could still see and use/skip these data. define('EBML_ID_CHANNELPOSITIONS', 0x347B); // [7D][7B] -- Table of horizontal angles for each successive channel, see appendix. define('EBML_ID_OUTPUTSAMPLINGFREQUENCY', 0x38B5); // [78][B5] -- Real output sampling frequency in Hz (used for SBR techniques). define('EBML_ID_TITLE', 0x3BA9); // [7B][A9] -- General name of the segment. define('EBML_ID_CHAPTERDISPLAY', 0x00); // [80] -- Contains all possible strings to use for the chapter display. define('EBML_ID_TRACKTYPE', 0x03); // [83] -- A set of track types coded on 8 bits (1: video, 2: audio, 3: complex, 0x10: logo, 0x11: subtitle, 0x12: buttons, 0x20: control). define('EBML_ID_CHAPSTRING', 0x05); // [85] -- Contains the string to use as the chapter atom. define('EBML_ID_CODECID', 0x06); // [86] -- An ID corresponding to the codec, see the codec page for more info. define('EBML_ID_FLAGDEFAULT', 0x08); // [88] -- Set if that track (audio, video or subs) SHOULD be used if no language found matches the user preference. define('EBML_ID_CHAPTERTRACKNUMBER', 0x09); // [89] -- UID of the Track to apply this chapter too. In the absense of a control track, choosing this chapter will select the listed Tracks and deselect unlisted tracks. Absense of this element indicates that the Chapter should be applied to any currently used Tracks. define('EBML_ID_CLUSTERSLICES', 0x0E); // [8E] -- Contains slices description. define('EBML_ID_CHAPTERTRACK', 0x0F); // [8F] -- List of tracks on which the chapter applies. If this element is not present, all tracks apply define('EBML_ID_CHAPTERTIMESTART', 0x11); // [91] -- Timecode of the start of Chapter (not scaled). define('EBML_ID_CHAPTERTIMEEND', 0x12); // [92] -- Timecode of the end of Chapter (timecode excluded, not scaled). define('EBML_ID_CUEREFTIME', 0x16); // [96] -- Timecode of the referenced Block. define('EBML_ID_CUEREFCLUSTER', 0x17); // [97] -- Position of the Cluster containing the referenced Block. define('EBML_ID_CHAPTERFLAGHIDDEN', 0x18); // [98] -- If a chapter is hidden (1), it should not be available to the user interface (but still to Control Tracks). define('EBML_ID_FLAGINTERLACED', 0x1A); // [9A] -- Set if the video is interlaced. define('EBML_ID_CLUSTERBLOCKDURATION', 0x1B); // [9B] -- The duration of the Block (based on TimecodeScale). This element is mandatory when DefaultDuration is set for the track. When not written and with no DefaultDuration, the value is assumed to be the difference between the timecode of this Block and the timecode of the next Block in "display" order (not coding order). This element can be useful at the end of a Track (as there is not other Block available), or when there is a break in a track like for subtitle tracks. define('EBML_ID_FLAGLACING', 0x1C); // [9C] -- Set if the track may contain blocks using lacing. define('EBML_ID_CHANNELS', 0x1F); // [9F] -- Numbers of channels in the track. define('EBML_ID_CLUSTERBLOCKGROUP', 0x20); // [A0] -- Basic container of information containing a single Block or BlockVirtual, and information specific to that Block/VirtualBlock. define('EBML_ID_CLUSTERBLOCK', 0x21); // [A1] -- Block containing the actual data to be rendered and a timecode relative to the Cluster Timecode. define('EBML_ID_CLUSTERBLOCKVIRTUAL', 0x22); // [A2] -- A Block with no data. It must be stored in the stream at the place the real Block should be in display order. define('EBML_ID_CLUSTERSIMPLEBLOCK', 0x23); // [A3] -- Similar to Block but without all the extra information, mostly used to reduced overhead when no extra feature is needed. define('EBML_ID_CLUSTERCODECSTATE', 0x24); // [A4] -- The new codec state to use. Data interpretation is private to the codec. This information should always be referenced by a seek entry. define('EBML_ID_CLUSTERBLOCKADDITIONAL', 0x25); // [A5] -- Interpreted by the codec as it wishes (using the BlockAddID). define('EBML_ID_CLUSTERBLOCKMORE', 0x26); // [A6] -- Contain the BlockAdditional and some parameters. define('EBML_ID_CLUSTERPOSITION', 0x27); // [A7] -- Position of the Cluster in the segment (0 in live broadcast streams). It might help to resynchronise offset on damaged streams. define('EBML_ID_CODECDECODEALL', 0x2A); // [AA] -- The codec can decode potentially damaged data. define('EBML_ID_CLUSTERPREVSIZE', 0x2B); // [AB] -- Size of the previous Cluster, in octets. Can be useful for backward playing. define('EBML_ID_TRACKENTRY', 0x2E); // [AE] -- Describes a track with all elements. define('EBML_ID_CLUSTERENCRYPTEDBLOCK', 0x2F); // [AF] -- Similar to SimpleBlock but the data inside the Block are Transformed (encrypt and/or signed). define('EBML_ID_PIXELWIDTH', 0x30); // [B0] -- Width of the encoded video frames in pixels. define('EBML_ID_CUETIME', 0x33); // [B3] -- Absolute timecode according to the segment time base. define('EBML_ID_SAMPLINGFREQUENCY', 0x35); // [B5] -- Sampling frequency in Hz. define('EBML_ID_CHAPTERATOM', 0x36); // [B6] -- Contains the atom information to use as the chapter atom (apply to all tracks). define('EBML_ID_CUETRACKPOSITIONS', 0x37); // [B7] -- Contain positions for different tracks corresponding to the timecode. define('EBML_ID_FLAGENABLED', 0x39); // [B9] -- Set if the track is used. define('EBML_ID_PIXELHEIGHT', 0x3A); // [BA] -- Height of the encoded video frames in pixels. define('EBML_ID_CUEPOINT', 0x3B); // [BB] -- Contains all information relative to a seek point in the segment. define('EBML_ID_CRC32', 0x3F); // [BF] -- The CRC is computed on all the data of the Master element it's in, regardless of its position. It's recommended to put the CRC value at the beggining of the Master element for easier reading. All level 1 elements should include a CRC-32. define('EBML_ID_CLUSTERBLOCKADDITIONID', 0x4B); // [CB] -- The ID of the BlockAdditional element (0 is the main Block). define('EBML_ID_CLUSTERLACENUMBER', 0x4C); // [CC] -- The reverse number of the frame in the lace (0 is the last frame, 1 is the next to last, etc). While there are a few files in the wild with this element, it is no longer in use and has been deprecated. Being able to interpret this element is not required for playback. define('EBML_ID_CLUSTERFRAMENUMBER', 0x4D); // [CD] -- The number of the frame to generate from this lace with this delay (allow you to generate many frames from the same Block/Frame). define('EBML_ID_CLUSTERDELAY', 0x4E); // [CE] -- The (scaled) delay to apply to the element. define('EBML_ID_CLUSTERDURATION', 0x4F); // [CF] -- The (scaled) duration to apply to the element. define('EBML_ID_TRACKNUMBER', 0x57); // [D7] -- The track number as used in the Block Header (using more than 127 tracks is not encouraged, though the design allows an unlimited number). define('EBML_ID_CUEREFERENCE', 0x5B); // [DB] -- The Clusters containing the required referenced Blocks. define('EBML_ID_VIDEO', 0x60); // [E0] -- Video settings. define('EBML_ID_AUDIO', 0x61); // [E1] -- Audio settings. define('EBML_ID_CLUSTERTIMESLICE', 0x68); // [E8] -- Contains extra time information about the data contained in the Block. While there are a few files in the wild with this element, it is no longer in use and has been deprecated. Being able to interpret this element is not required for playback. define('EBML_ID_CUECODECSTATE', 0x6A); // [EA] -- The position of the Codec State corresponding to this Cue element. 0 means that the data is taken from the initial Track Entry. define('EBML_ID_CUEREFCODECSTATE', 0x6B); // [EB] -- The position of the Codec State corresponding to this referenced element. 0 means that the data is taken from the initial Track Entry. define('EBML_ID_VOID', 0x6C); // [EC] -- Used to void damaged data, to avoid unexpected behaviors when using damaged data. The content is discarded. Also used to reserve space in a sub-element for later use. define('EBML_ID_CLUSTERTIMECODE', 0x67); // [E7] -- Absolute timecode of the cluster (based on TimecodeScale). define('EBML_ID_CLUSTERBLOCKADDID', 0x6E); // [EE] -- An ID to identify the BlockAdditional level. define('EBML_ID_CUECLUSTERPOSITION', 0x71); // [F1] -- The position of the Cluster containing the required Block. define('EBML_ID_CUETRACK', 0x77); // [F7] -- The track for which a position is given. define('EBML_ID_CLUSTERREFERENCEPRIORITY', 0x7A); // [FA] -- This frame is referenced and has the specified cache priority. In cache only a frame of the same or higher priority can replace this frame. A value of 0 means the frame is not referenced. define('EBML_ID_CLUSTERREFERENCEBLOCK', 0x7B); // [FB] -- Timecode of another frame used as a reference (ie: B or P frame). The timecode is relative to the block it's attached to. define('EBML_ID_CLUSTERREFERENCEVIRTUAL', 0x7D); // [FD] -- Relative position of the data that should be in position of the virtual block. /** * @tutorial http://www.matroska.org/technical/specs/index.html * * @todo Rewrite EBML parser to reduce it's size and honor default element values * @todo After rewrite implement stream size calculation, that will provide additional useful info and enable AAC/FLAC audio bitrate detection */ class getid3_matroska extends getid3_handler { /** * If true, do not return information about CLUSTER chunks, since there's a lot of them * and they're not usually useful [default: TRUE]. * * @var bool */ public $hide_clusters = true; /** * True to parse the whole file, not only header [default: FALSE]. * * @var bool */ public $parse_whole_file = false; /* * Private parser settings/placeholders. */ private $EBMLbuffer = ''; private $EBMLbuffer_offset = 0; private $EBMLbuffer_length = 0; private $current_offset = 0; private $unuseful_elements = array(EBML_ID_CRC32, EBML_ID_VOID); /** * @return bool */ public function Analyze() { $info = &$this->getid3->info; // parse container try { $this->parseEBML($info); } catch (Exception $e) { $this->error('EBML parser: '.$e->getMessage()); } // calculate playtime if (isset($info['matroska']['info']) && is_array($info['matroska']['info'])) { foreach ($info['matroska']['info'] as $key => $infoarray) { if (isset($infoarray['Duration'])) { // TimecodeScale is how many nanoseconds each Duration unit is $info['playtime_seconds'] = $infoarray['Duration'] * ((isset($infoarray['TimecodeScale']) ? $infoarray['TimecodeScale'] : 1000000) / 1000000000); break; } } } // extract tags if (isset($info['matroska']['tags']) && is_array($info['matroska']['tags'])) { foreach ($info['matroska']['tags'] as $key => $infoarray) { $this->ExtractCommentsSimpleTag($infoarray); } } // process tracks if (isset($info['matroska']['tracks']['tracks']) && is_array($info['matroska']['tracks']['tracks'])) { foreach ($info['matroska']['tracks']['tracks'] as $key => $trackarray) { $track_info = array(); $track_info['dataformat'] = self::CodecIDtoCommonName($trackarray['CodecID']); $track_info['default'] = (isset($trackarray['FlagDefault']) ? $trackarray['FlagDefault'] : true); if (isset($trackarray['Name'])) { $track_info['name'] = $trackarray['Name']; } switch ($trackarray['TrackType']) { case 1: // Video $track_info['resolution_x'] = $trackarray['PixelWidth']; $track_info['resolution_y'] = $trackarray['PixelHeight']; $track_info['display_unit'] = self::displayUnit(isset($trackarray['DisplayUnit']) ? $trackarray['DisplayUnit'] : 0); $track_info['display_x'] = (isset($trackarray['DisplayWidth']) ? $trackarray['DisplayWidth'] : $trackarray['PixelWidth']); $track_info['display_y'] = (isset($trackarray['DisplayHeight']) ? $trackarray['DisplayHeight'] : $trackarray['PixelHeight']); if (isset($trackarray['PixelCropBottom'])) { $track_info['crop_bottom'] = $trackarray['PixelCropBottom']; } if (isset($trackarray['PixelCropTop'])) { $track_info['crop_top'] = $trackarray['PixelCropTop']; } if (isset($trackarray['PixelCropLeft'])) { $track_info['crop_left'] = $trackarray['PixelCropLeft']; } if (isset($trackarray['PixelCropRight'])) { $track_info['crop_right'] = $trackarray['PixelCropRight']; } if (!empty($trackarray['DefaultDuration'])) { $track_info['frame_rate'] = round(1000000000 / $trackarray['DefaultDuration'], 3); } if (isset($trackarray['CodecName'])) { $track_info['codec'] = $trackarray['CodecName']; } switch ($trackarray['CodecID']) { case 'V_MS/VFW/FOURCC': getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.audio-video.riff.php', __FILE__, true); $parsed = getid3_riff::ParseBITMAPINFOHEADER($trackarray['CodecPrivate']); $track_info['codec'] = getid3_riff::fourccLookup($parsed['fourcc']); $info['matroska']['track_codec_parsed'][$trackarray['TrackNumber']] = $parsed; break; /*case 'V_MPEG4/ISO/AVC': $h264['profile'] = getid3_lib::BigEndian2Int(substr($trackarray['CodecPrivate'], 1, 1)); $h264['level'] = getid3_lib::BigEndian2Int(substr($trackarray['CodecPrivate'], 3, 1)); $rn = getid3_lib::BigEndian2Int(substr($trackarray['CodecPrivate'], 4, 1)); $h264['NALUlength'] = ($rn & 3) + 1; $rn = getid3_lib::BigEndian2Int(substr($trackarray['CodecPrivate'], 5, 1)); $nsps = ($rn & 31); $offset = 6; for ($i = 0; $i < $nsps; $i ++) { $length = getid3_lib::BigEndian2Int(substr($trackarray['CodecPrivate'], $offset, 2)); $h264['SPS'][] = substr($trackarray['CodecPrivate'], $offset + 2, $length); $offset += 2 + $length; } $npps = getid3_lib::BigEndian2Int(substr($trackarray['CodecPrivate'], $offset, 1)); $offset += 1; for ($i = 0; $i < $npps; $i ++) { $length = getid3_lib::BigEndian2Int(substr($trackarray['CodecPrivate'], $offset, 2)); $h264['PPS'][] = substr($trackarray['CodecPrivate'], $offset + 2, $length); $offset += 2 + $length; } $info['matroska']['track_codec_parsed'][$trackarray['TrackNumber']] = $h264; break;*/ } $info['video']['streams'][$trackarray['TrackUID']] = $track_info; break; case 2: // Audio $track_info['sample_rate'] = (isset($trackarray['SamplingFrequency']) ? $trackarray['SamplingFrequency'] : 8000.0); $track_info['channels'] = (isset($trackarray['Channels']) ? $trackarray['Channels'] : 1); $track_info['language'] = (isset($trackarray['Language']) ? $trackarray['Language'] : 'eng'); if (isset($trackarray['BitDepth'])) { $track_info['bits_per_sample'] = $trackarray['BitDepth']; } if (isset($trackarray['CodecName'])) { $track_info['codec'] = $trackarray['CodecName']; } switch ($trackarray['CodecID']) { case 'A_PCM/INT/LIT': case 'A_PCM/INT/BIG': $track_info['bitrate'] = $track_info['sample_rate'] * $track_info['channels'] * $trackarray['BitDepth']; break; case 'A_AC3': case 'A_EAC3': case 'A_DTS': case 'A_MPEG/L3': case 'A_MPEG/L2': case 'A_FLAC': $module_dataformat = ($track_info['dataformat'] == 'mp2' ? 'mp3' : ($track_info['dataformat'] == 'eac3' ? 'ac3' : $track_info['dataformat'])); getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.audio.'.$module_dataformat.'.php', __FILE__, true); if (!isset($info['matroska']['track_data_offsets'][$trackarray['TrackNumber']])) { $this->warning('Unable to parse audio data ['.basename(__FILE__).':'.__LINE__.'] because $info[matroska][track_data_offsets]['.$trackarray['TrackNumber'].'] not set'); break; } // create temp instance $getid3_temp = new getID3(); if ($track_info['dataformat'] != 'flac') { $getid3_temp->openfile($this->getid3->filename, $this->getid3->info['filesize'], $this->getid3->fp); } $getid3_temp->info['avdataoffset'] = $info['matroska']['track_data_offsets'][$trackarray['TrackNumber']]['offset']; if ($track_info['dataformat'][0] == 'm' || $track_info['dataformat'] == 'flac') { $getid3_temp->info['avdataend'] = $info['matroska']['track_data_offsets'][$trackarray['TrackNumber']]['offset'] + $info['matroska']['track_data_offsets'][$trackarray['TrackNumber']]['length']; } // analyze $class = 'getid3_'.$module_dataformat; $header_data_key = $track_info['dataformat'][0] == 'm' ? 'mpeg' : $track_info['dataformat']; $getid3_audio = new $class($getid3_temp, __CLASS__); if ($track_info['dataformat'] == 'flac') { $getid3_audio->AnalyzeString($trackarray['CodecPrivate']); } else { $getid3_audio->Analyze(); } if (!empty($getid3_temp->info[$header_data_key])) { $info['matroska']['track_codec_parsed'][$trackarray['TrackNumber']] = $getid3_temp->info[$header_data_key]; if (isset($getid3_temp->info['audio']) && is_array($getid3_temp->info['audio'])) { foreach ($getid3_temp->info['audio'] as $sub_key => $value) { $track_info[$sub_key] = $value; } } } else { $this->warning('Unable to parse audio data ['.basename(__FILE__).':'.__LINE__.'] because '.$class.'::Analyze() failed at offset '.$getid3_temp->info['avdataoffset']); } // copy errors and warnings if (!empty($getid3_temp->info['error'])) { foreach ($getid3_temp->info['error'] as $newerror) { $this->warning($class.'() says: ['.$newerror.']'); } } if (!empty($getid3_temp->info['warning'])) { foreach ($getid3_temp->info['warning'] as $newerror) { $this->warning($class.'() says: ['.$newerror.']'); } } unset($getid3_temp, $getid3_audio); break; case 'A_AAC': case 'A_AAC/MPEG2/LC': case 'A_AAC/MPEG2/LC/SBR': case 'A_AAC/MPEG4/LC': case 'A_AAC/MPEG4/LC/SBR': $this->warning($trackarray['CodecID'].' audio data contains no header, audio/video bitrates can\'t be calculated'); break; case 'A_VORBIS': if (!isset($trackarray['CodecPrivate'])) { $this->warning('Unable to parse audio data ['.basename(__FILE__).':'.__LINE__.'] because CodecPrivate data not set'); break; } $vorbis_offset = strpos($trackarray['CodecPrivate'], 'vorbis', 1); if ($vorbis_offset === false) { $this->warning('Unable to parse audio data ['.basename(__FILE__).':'.__LINE__.'] because CodecPrivate data does not contain "vorbis" keyword'); break; } $vorbis_offset -= 1; getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.audio.ogg.php', __FILE__, true); // create temp instance $getid3_temp = new getID3(); // analyze $getid3_ogg = new getid3_ogg($getid3_temp); $oggpageinfo['page_seqno'] = 0; $getid3_ogg->ParseVorbisPageHeader($trackarray['CodecPrivate'], $vorbis_offset, $oggpageinfo); if (!empty($getid3_temp->info['ogg'])) { $info['matroska']['track_codec_parsed'][$trackarray['TrackNumber']] = $getid3_temp->info['ogg']; if (isset($getid3_temp->info['audio']) && is_array($getid3_temp->info['audio'])) { foreach ($getid3_temp->info['audio'] as $sub_key => $value) { $track_info[$sub_key] = $value; } } } // copy errors and warnings if (!empty($getid3_temp->info['error'])) { foreach ($getid3_temp->info['error'] as $newerror) { $this->warning('getid3_ogg() says: ['.$newerror.']'); } } if (!empty($getid3_temp->info['warning'])) { foreach ($getid3_temp->info['warning'] as $newerror) { $this->warning('getid3_ogg() says: ['.$newerror.']'); } } if (!empty($getid3_temp->info['ogg']['bitrate_nominal'])) { $track_info['bitrate'] = $getid3_temp->info['ogg']['bitrate_nominal']; } unset($getid3_temp, $getid3_ogg, $oggpageinfo, $vorbis_offset); break; case 'A_MS/ACM': getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.audio-video.riff.php', __FILE__, true); $parsed = getid3_riff::parseWAVEFORMATex($trackarray['CodecPrivate']); foreach ($parsed as $sub_key => $value) { if ($sub_key != 'raw') { $track_info[$sub_key] = $value; } } $info['matroska']['track_codec_parsed'][$trackarray['TrackNumber']] = $parsed; break; default: $this->warning('Unhandled audio type "'.(isset($trackarray['CodecID']) ? $trackarray['CodecID'] : '').'"'); break; } $info['audio']['streams'][$trackarray['TrackUID']] = $track_info; break; } } if (!empty($info['video']['streams'])) { $info['video'] = self::getDefaultStreamInfo($info['video']['streams']); } if (!empty($info['audio']['streams'])) { $info['audio'] = self::getDefaultStreamInfo($info['audio']['streams']); } } // process attachments if (isset($info['matroska']['attachments']) && $this->getid3->option_save_attachments !== getID3::ATTACHMENTS_NONE) { foreach ($info['matroska']['attachments'] as $i => $entry) { if (strpos($entry['FileMimeType'], 'image/') === 0 && !empty($entry['FileData'])) { $info['matroska']['comments']['picture'][] = array('data' => $entry['FileData'], 'image_mime' => $entry['FileMimeType'], 'filename' => $entry['FileName']); } } } // determine mime type if (!empty($info['video']['streams'])) { $info['mime_type'] = ($info['matroska']['doctype'] == 'webm' ? 'video/webm' : 'video/x-matroska'); } elseif (!empty($info['audio']['streams'])) { $info['mime_type'] = ($info['matroska']['doctype'] == 'webm' ? 'audio/webm' : 'audio/x-matroska'); } elseif (isset($info['mime_type'])) { unset($info['mime_type']); } // use _STATISTICS_TAGS if available to set audio/video bitrates if (!empty($info['matroska']['tags'])) { $_STATISTICS_byTrackUID = array(); foreach ($info['matroska']['tags'] as $key1 => $value1) { if (!empty($value1['Targets']['TagTrackUID'][0]) && !empty($value1['SimpleTag'])) { foreach ($value1['SimpleTag'] as $key2 => $value2) { if (!empty($value2['TagName']) && isset($value2['TagString'])) { $_STATISTICS_byTrackUID[$value1['Targets']['TagTrackUID'][0]][$value2['TagName']] = $value2['TagString']; } } } } foreach (array('audio','video') as $avtype) { if (!empty($info[$avtype]['streams'])) { foreach ($info[$avtype]['streams'] as $trackUID => $trackdata) { if (!isset($trackdata['bitrate']) && !empty($_STATISTICS_byTrackUID[$trackUID]['BPS'])) { $info[$avtype]['streams'][$trackUID]['bitrate'] = (int) $_STATISTICS_byTrackUID[$trackUID]['BPS']; @$info[$avtype]['bitrate'] += $info[$avtype]['streams'][$trackUID]['bitrate']; } } } } } return true; } /** * @param array $info */ private function parseEBML(&$info) { // http://www.matroska.org/technical/specs/index.html#EBMLBasics $this->current_offset = $info['avdataoffset']; while ($this->getEBMLelement($top_element, $info['avdataend'])) { switch ($top_element['id']) { case EBML_ID_EBML: $info['matroska']['header']['offset'] = $top_element['offset']; $info['matroska']['header']['length'] = $top_element['length']; while ($this->getEBMLelement($element_data, $top_element['end'], true)) { switch ($element_data['id']) { case EBML_ID_EBMLVERSION: case EBML_ID_EBMLREADVERSION: case EBML_ID_EBMLMAXIDLENGTH: case EBML_ID_EBMLMAXSIZELENGTH: case EBML_ID_DOCTYPEVERSION: case EBML_ID_DOCTYPEREADVERSION: $element_data['data'] = getid3_lib::BigEndian2Int($element_data['data']); break; case EBML_ID_DOCTYPE: $element_data['data'] = getid3_lib::trimNullByte($element_data['data']); $info['matroska']['doctype'] = $element_data['data']; $info['fileformat'] = $element_data['data']; break; default: $this->unhandledElement('header', __LINE__, $element_data); break; } unset($element_data['offset'], $element_data['end']); $info['matroska']['header']['elements'][] = $element_data; } break; case EBML_ID_SEGMENT: $info['matroska']['segment'][0]['offset'] = $top_element['offset']; $info['matroska']['segment'][0]['length'] = $top_element['length']; while ($this->getEBMLelement($element_data, $top_element['end'])) { if ($element_data['id'] != EBML_ID_CLUSTER || !$this->hide_clusters) { // collect clusters only if required $info['matroska']['segments'][] = $element_data; } switch ($element_data['id']) { case EBML_ID_SEEKHEAD: // Contains the position of other level 1 elements. while ($this->getEBMLelement($seek_entry, $element_data['end'])) { switch ($seek_entry['id']) { case EBML_ID_SEEK: // Contains a single seek entry to an EBML element while ($this->getEBMLelement($sub_seek_entry, $seek_entry['end'], true)) { switch ($sub_seek_entry['id']) { case EBML_ID_SEEKID: $seek_entry['target_id'] = self::EBML2Int($sub_seek_entry['data']); $seek_entry['target_name'] = self::EBMLidName($seek_entry['target_id']); break; case EBML_ID_SEEKPOSITION: $seek_entry['target_offset'] = $element_data['offset'] + getid3_lib::BigEndian2Int($sub_seek_entry['data']); break; default: $this->unhandledElement('seekhead.seek', __LINE__, $sub_seek_entry); } break; } if (!isset($seek_entry['target_id'])) { $this->warning('seek_entry[target_id] unexpectedly not set at '.$seek_entry['offset']); break; } if (($seek_entry['target_id'] != EBML_ID_CLUSTER) || !$this->hide_clusters) { // collect clusters only if required $info['matroska']['seek'][] = $seek_entry; } break; default: $this->unhandledElement('seekhead', __LINE__, $seek_entry); break; } } break; case EBML_ID_TRACKS: // A top-level block of information with many tracks described. $info['matroska']['tracks'] = $element_data; while ($this->getEBMLelement($track_entry, $element_data['end'])) { switch ($track_entry['id']) { case EBML_ID_TRACKENTRY: //subelements: Describes a track with all elements. while ($this->getEBMLelement($subelement, $track_entry['end'], array(EBML_ID_VIDEO, EBML_ID_AUDIO, EBML_ID_CONTENTENCODINGS, EBML_ID_CODECPRIVATE))) { switch ($subelement['id']) { case EBML_ID_TRACKUID: $track_entry[$subelement['id_name']] = getid3_lib::PrintHexBytes($subelement['data'], true, false); break; case EBML_ID_TRACKNUMBER: case EBML_ID_TRACKTYPE: case EBML_ID_MINCACHE: case EBML_ID_MAXCACHE: case EBML_ID_MAXBLOCKADDITIONID: case EBML_ID_DEFAULTDURATION: // nanoseconds per frame $track_entry[$subelement['id_name']] = getid3_lib::BigEndian2Int($subelement['data']); break; case EBML_ID_TRACKTIMECODESCALE: $track_entry[$subelement['id_name']] = getid3_lib::BigEndian2Float($subelement['data']); break; case EBML_ID_CODECID: case EBML_ID_LANGUAGE: case EBML_ID_NAME: case EBML_ID_CODECNAME: $track_entry[$subelement['id_name']] = getid3_lib::trimNullByte($subelement['data']); break; case EBML_ID_CODECPRIVATE: $track_entry[$subelement['id_name']] = $this->readEBMLelementData($subelement['length'], true); break; case EBML_ID_FLAGENABLED: case EBML_ID_FLAGDEFAULT: case EBML_ID_FLAGFORCED: case EBML_ID_FLAGLACING: case EBML_ID_CODECDECODEALL: $track_entry[$subelement['id_name']] = (bool) getid3_lib::BigEndian2Int($subelement['data']); break; case EBML_ID_VIDEO: while ($this->getEBMLelement($sub_subelement, $subelement['end'], true)) { switch ($sub_subelement['id']) { case EBML_ID_PIXELWIDTH: case EBML_ID_PIXELHEIGHT: case EBML_ID_PIXELCROPBOTTOM: case EBML_ID_PIXELCROPTOP: case EBML_ID_PIXELCROPLEFT: case EBML_ID_PIXELCROPRIGHT: case EBML_ID_DISPLAYWIDTH: case EBML_ID_DISPLAYHEIGHT: case EBML_ID_DISPLAYUNIT: case EBML_ID_ASPECTRATIOTYPE: case EBML_ID_STEREOMODE: case EBML_ID_OLDSTEREOMODE: $track_entry[$sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_subelement['data']); break; case EBML_ID_FLAGINTERLACED: $track_entry[$sub_subelement['id_name']] = (bool)getid3_lib::BigEndian2Int($sub_subelement['data']); break; case EBML_ID_GAMMAVALUE: $track_entry[$sub_subelement['id_name']] = getid3_lib::BigEndian2Float($sub_subelement['data']); break; case EBML_ID_COLOURSPACE: $track_entry[$sub_subelement['id_name']] = getid3_lib::trimNullByte($sub_subelement['data']); break; default: $this->unhandledElement('track.video', __LINE__, $sub_subelement); break; } } break; case EBML_ID_AUDIO: while ($this->getEBMLelement($sub_subelement, $subelement['end'], true)) { switch ($sub_subelement['id']) { case EBML_ID_CHANNELS: case EBML_ID_BITDEPTH: $track_entry[$sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_subelement['data']); break; case EBML_ID_SAMPLINGFREQUENCY: case EBML_ID_OUTPUTSAMPLINGFREQUENCY: $track_entry[$sub_subelement['id_name']] = getid3_lib::BigEndian2Float($sub_subelement['data']); break; case EBML_ID_CHANNELPOSITIONS: $track_entry[$sub_subelement['id_name']] = getid3_lib::trimNullByte($sub_subelement['data']); break; default: $this->unhandledElement('track.audio', __LINE__, $sub_subelement); break; } } break; case EBML_ID_CONTENTENCODINGS: while ($this->getEBMLelement($sub_subelement, $subelement['end'])) { switch ($sub_subelement['id']) { case EBML_ID_CONTENTENCODING: while ($this->getEBMLelement($sub_sub_subelement, $sub_subelement['end'], array(EBML_ID_CONTENTCOMPRESSION, EBML_ID_CONTENTENCRYPTION))) { switch ($sub_sub_subelement['id']) { case EBML_ID_CONTENTENCODINGORDER: case EBML_ID_CONTENTENCODINGSCOPE: case EBML_ID_CONTENTENCODINGTYPE: $track_entry[$sub_subelement['id_name']][$sub_sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_sub_subelement['data']); break; case EBML_ID_CONTENTCOMPRESSION: while ($this->getEBMLelement($sub_sub_sub_subelement, $sub_sub_subelement['end'], true)) { switch ($sub_sub_sub_subelement['id']) { case EBML_ID_CONTENTCOMPALGO: $track_entry[$sub_subelement['id_name']][$sub_sub_subelement['id_name']][$sub_sub_sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_sub_sub_subelement['data']); break; case EBML_ID_CONTENTCOMPSETTINGS: $track_entry[$sub_subelement['id_name']][$sub_sub_subelement['id_name']][$sub_sub_sub_subelement['id_name']] = $sub_sub_sub_subelement['data']; break; default: $this->unhandledElement('track.contentencodings.contentencoding.contentcompression', __LINE__, $sub_sub_sub_subelement); break; } } break; case EBML_ID_CONTENTENCRYPTION: while ($this->getEBMLelement($sub_sub_sub_subelement, $sub_sub_subelement['end'], true)) { switch ($sub_sub_sub_subelement['id']) { case EBML_ID_CONTENTENCALGO: case EBML_ID_CONTENTSIGALGO: case EBML_ID_CONTENTSIGHASHALGO: $track_entry[$sub_subelement['id_name']][$sub_sub_subelement['id_name']][$sub_sub_sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_sub_sub_subelement['data']); break; case EBML_ID_CONTENTENCKEYID: case EBML_ID_CONTENTSIGNATURE: case EBML_ID_CONTENTSIGKEYID: $track_entry[$sub_subelement['id_name']][$sub_sub_subelement['id_name']][$sub_sub_sub_subelement['id_name']] = $sub_sub_sub_subelement['data']; break; default: $this->unhandledElement('track.contentencodings.contentencoding.contentcompression', __LINE__, $sub_sub_sub_subelement); break; } } break; default: $this->unhandledElement('track.contentencodings.contentencoding', __LINE__, $sub_sub_subelement); break; } } break; default: $this->unhandledElement('track.contentencodings', __LINE__, $sub_subelement); break; } } break; default: $this->unhandledElement('track', __LINE__, $subelement); break; } } $info['matroska']['tracks']['tracks'][] = $track_entry; break; default: $this->unhandledElement('tracks', __LINE__, $track_entry); break; } } break; case EBML_ID_INFO: // Contains miscellaneous general information and statistics on the file. $info_entry = array(); while ($this->getEBMLelement($subelement, $element_data['end'], true)) { switch ($subelement['id']) { case EBML_ID_TIMECODESCALE: $info_entry[$subelement['id_name']] = getid3_lib::BigEndian2Int($subelement['data']); break; case EBML_ID_DURATION: $info_entry[$subelement['id_name']] = getid3_lib::BigEndian2Float($subelement['data']); break; case EBML_ID_DATEUTC: $info_entry[$subelement['id_name']] = getid3_lib::BigEndian2Int($subelement['data']); $info_entry[$subelement['id_name'].'_unix'] = self::EBMLdate2unix($info_entry[$subelement['id_name']]); break; case EBML_ID_SEGMENTUID: case EBML_ID_PREVUID: case EBML_ID_NEXTUID: $info_entry[$subelement['id_name']] = getid3_lib::trimNullByte($subelement['data']); break; case EBML_ID_SEGMENTFAMILY: $info_entry[$subelement['id_name']][] = getid3_lib::trimNullByte($subelement['data']); break; case EBML_ID_SEGMENTFILENAME: case EBML_ID_PREVFILENAME: case EBML_ID_NEXTFILENAME: case EBML_ID_TITLE: case EBML_ID_MUXINGAPP: case EBML_ID_WRITINGAPP: $info_entry[$subelement['id_name']] = getid3_lib::trimNullByte($subelement['data']); $info['matroska']['comments'][strtolower($subelement['id_name'])][] = $info_entry[$subelement['id_name']]; break; case EBML_ID_CHAPTERTRANSLATE: $chaptertranslate_entry = array(); while ($this->getEBMLelement($sub_subelement, $subelement['end'], true)) { switch ($sub_subelement['id']) { case EBML_ID_CHAPTERTRANSLATEEDITIONUID: $chaptertranslate_entry[$sub_subelement['id_name']][] = getid3_lib::BigEndian2Int($sub_subelement['data']); break; case EBML_ID_CHAPTERTRANSLATECODEC: $chaptertranslate_entry[$sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_subelement['data']); break; case EBML_ID_CHAPTERTRANSLATEID: $chaptertranslate_entry[$sub_subelement['id_name']] = getid3_lib::trimNullByte($sub_subelement['data']); break; default: $this->unhandledElement('info.chaptertranslate', __LINE__, $sub_subelement); break; } } $info_entry[$subelement['id_name']] = $chaptertranslate_entry; break; default: $this->unhandledElement('info', __LINE__, $subelement); break; } } $info['matroska']['info'][] = $info_entry; break; case EBML_ID_CUES: // A top-level element to speed seeking access. All entries are local to the segment. Should be mandatory for non "live" streams. if ($this->hide_clusters) { // do not parse cues if hide clusters is "ON" till they point to clusters anyway $this->current_offset = $element_data['end']; break; } $cues_entry = array(); while ($this->getEBMLelement($subelement, $element_data['end'])) { switch ($subelement['id']) { case EBML_ID_CUEPOINT: $cuepoint_entry = array(); while ($this->getEBMLelement($sub_subelement, $subelement['end'], array(EBML_ID_CUETRACKPOSITIONS))) { switch ($sub_subelement['id']) { case EBML_ID_CUETRACKPOSITIONS: $cuetrackpositions_entry = array(); while ($this->getEBMLelement($sub_sub_subelement, $sub_subelement['end'], true)) { switch ($sub_sub_subelement['id']) { case EBML_ID_CUETRACK: case EBML_ID_CUECLUSTERPOSITION: case EBML_ID_CUEBLOCKNUMBER: case EBML_ID_CUECODECSTATE: $cuetrackpositions_entry[$sub_sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_sub_subelement['data']); break; default: $this->unhandledElement('cues.cuepoint.cuetrackpositions', __LINE__, $sub_sub_subelement); break; } } $cuepoint_entry[$sub_subelement['id_name']][] = $cuetrackpositions_entry; break; case EBML_ID_CUETIME: $cuepoint_entry[$sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_subelement['data']); break; default: $this->unhandledElement('cues.cuepoint', __LINE__, $sub_subelement); break; } } $cues_entry[] = $cuepoint_entry; break; default: $this->unhandledElement('cues', __LINE__, $subelement); break; } } $info['matroska']['cues'] = $cues_entry; break; case EBML_ID_TAGS: // Element containing elements specific to Tracks/Chapters. $tags_entry = array(); while ($this->getEBMLelement($subelement, $element_data['end'], false)) { switch ($subelement['id']) { case EBML_ID_TAG: $tag_entry = array(); while ($this->getEBMLelement($sub_subelement, $subelement['end'], false)) { switch ($sub_subelement['id']) { case EBML_ID_TARGETS: $targets_entry = array(); while ($this->getEBMLelement($sub_sub_subelement, $sub_subelement['end'], true)) { switch ($sub_sub_subelement['id']) { case EBML_ID_TARGETTYPEVALUE: $targets_entry[$sub_sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_sub_subelement['data']); $targets_entry[strtolower($sub_sub_subelement['id_name']).'_long'] = self::TargetTypeValue($targets_entry[$sub_sub_subelement['id_name']]); break; case EBML_ID_TARGETTYPE: $targets_entry[$sub_sub_subelement['id_name']] = $sub_sub_subelement['data']; break; case EBML_ID_TAGTRACKUID: case EBML_ID_TAGEDITIONUID: case EBML_ID_TAGCHAPTERUID: case EBML_ID_TAGATTACHMENTUID: $targets_entry[$sub_sub_subelement['id_name']][] = getid3_lib::PrintHexBytes($sub_sub_subelement['data'], true, false); break; default: $this->unhandledElement('tags.tag.targets', __LINE__, $sub_sub_subelement); break; } } $tag_entry[$sub_subelement['id_name']] = $targets_entry; break; case EBML_ID_SIMPLETAG: $tag_entry[$sub_subelement['id_name']][] = $this->HandleEMBLSimpleTag($sub_subelement['end']); break; default: $this->unhandledElement('tags.tag', __LINE__, $sub_subelement); break; } } $tags_entry[] = $tag_entry; break; default: $this->unhandledElement('tags', __LINE__, $subelement); break; } } $info['matroska']['tags'] = $tags_entry; break; case EBML_ID_ATTACHMENTS: // Contain attached files. while ($this->getEBMLelement($subelement, $element_data['end'])) { switch ($subelement['id']) { case EBML_ID_ATTACHEDFILE: $attachedfile_entry = array(); while ($this->getEBMLelement($sub_subelement, $subelement['end'], array(EBML_ID_FILEDATA))) { switch ($sub_subelement['id']) { case EBML_ID_FILEDESCRIPTION: case EBML_ID_FILENAME: case EBML_ID_FILEMIMETYPE: $attachedfile_entry[$sub_subelement['id_name']] = $sub_subelement['data']; break; case EBML_ID_FILEDATA: $attachedfile_entry['data_offset'] = $this->current_offset; $attachedfile_entry['data_length'] = $sub_subelement['length']; $attachedfile_entry[$sub_subelement['id_name']] = $this->saveAttachment( $attachedfile_entry['FileName'], $attachedfile_entry['data_offset'], $attachedfile_entry['data_length']); $this->current_offset = $sub_subelement['end']; break; case EBML_ID_FILEUID: $attachedfile_entry[$sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_subelement['data']); break; default: $this->unhandledElement('attachments.attachedfile', __LINE__, $sub_subelement); break; } } $info['matroska']['attachments'][] = $attachedfile_entry; break; default: $this->unhandledElement('attachments', __LINE__, $subelement); break; } } break; case EBML_ID_CHAPTERS: while ($this->getEBMLelement($subelement, $element_data['end'])) { switch ($subelement['id']) { case EBML_ID_EDITIONENTRY: $editionentry_entry = array(); while ($this->getEBMLelement($sub_subelement, $subelement['end'], array(EBML_ID_CHAPTERATOM))) { switch ($sub_subelement['id']) { case EBML_ID_EDITIONUID: $editionentry_entry[$sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_subelement['data']); break; case EBML_ID_EDITIONFLAGHIDDEN: case EBML_ID_EDITIONFLAGDEFAULT: case EBML_ID_EDITIONFLAGORDERED: $editionentry_entry[$sub_subelement['id_name']] = (bool)getid3_lib::BigEndian2Int($sub_subelement['data']); break; case EBML_ID_CHAPTERATOM: $chapteratom_entry = array(); while ($this->getEBMLelement($sub_sub_subelement, $sub_subelement['end'], array(EBML_ID_CHAPTERTRACK, EBML_ID_CHAPTERDISPLAY))) { switch ($sub_sub_subelement['id']) { case EBML_ID_CHAPTERSEGMENTUID: case EBML_ID_CHAPTERSEGMENTEDITIONUID: $chapteratom_entry[$sub_sub_subelement['id_name']] = $sub_sub_subelement['data']; break; case EBML_ID_CHAPTERFLAGENABLED: case EBML_ID_CHAPTERFLAGHIDDEN: $chapteratom_entry[$sub_sub_subelement['id_name']] = (bool)getid3_lib::BigEndian2Int($sub_sub_subelement['data']); break; case EBML_ID_CHAPTERUID: case EBML_ID_CHAPTERTIMESTART: case EBML_ID_CHAPTERTIMEEND: $chapteratom_entry[$sub_sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_sub_subelement['data']); break; case EBML_ID_CHAPTERTRACK: $chaptertrack_entry = array(); while ($this->getEBMLelement($sub_sub_sub_subelement, $sub_sub_subelement['end'], true)) { switch ($sub_sub_sub_subelement['id']) { case EBML_ID_CHAPTERTRACKNUMBER: $chaptertrack_entry[$sub_sub_sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_sub_sub_subelement['data']); break; default: $this->unhandledElement('chapters.editionentry.chapteratom.chaptertrack', __LINE__, $sub_sub_sub_subelement); break; } } $chapteratom_entry[$sub_sub_subelement['id_name']][] = $chaptertrack_entry; break; case EBML_ID_CHAPTERDISPLAY: $chapterdisplay_entry = array(); while ($this->getEBMLelement($sub_sub_sub_subelement, $sub_sub_subelement['end'], true)) { switch ($sub_sub_sub_subelement['id']) { case EBML_ID_CHAPSTRING: case EBML_ID_CHAPLANGUAGE: case EBML_ID_CHAPCOUNTRY: $chapterdisplay_entry[$sub_sub_sub_subelement['id_name']] = $sub_sub_sub_subelement['data']; break; default: $this->unhandledElement('chapters.editionentry.chapteratom.chapterdisplay', __LINE__, $sub_sub_sub_subelement); break; } } $chapteratom_entry[$sub_sub_subelement['id_name']][] = $chapterdisplay_entry; break; default: $this->unhandledElement('chapters.editionentry.chapteratom', __LINE__, $sub_sub_subelement); break; } } $editionentry_entry[$sub_subelement['id_name']][] = $chapteratom_entry; break; default: $this->unhandledElement('chapters.editionentry', __LINE__, $sub_subelement); break; } } $info['matroska']['chapters'][] = $editionentry_entry; break; default: $this->unhandledElement('chapters', __LINE__, $subelement); break; } } break; case EBML_ID_CLUSTER: // The lower level element containing the (monolithic) Block structure. $cluster_entry = array(); while ($this->getEBMLelement($subelement, $element_data['end'], array(EBML_ID_CLUSTERSILENTTRACKS, EBML_ID_CLUSTERBLOCKGROUP, EBML_ID_CLUSTERSIMPLEBLOCK))) { switch ($subelement['id']) { case EBML_ID_CLUSTERTIMECODE: case EBML_ID_CLUSTERPOSITION: case EBML_ID_CLUSTERPREVSIZE: $cluster_entry[$subelement['id_name']] = getid3_lib::BigEndian2Int($subelement['data']); break; case EBML_ID_CLUSTERSILENTTRACKS: $cluster_silent_tracks = array(); while ($this->getEBMLelement($sub_subelement, $subelement['end'], true)) { switch ($sub_subelement['id']) { case EBML_ID_CLUSTERSILENTTRACKNUMBER: $cluster_silent_tracks[] = getid3_lib::BigEndian2Int($sub_subelement['data']); break; default: $this->unhandledElement('cluster.silenttracks', __LINE__, $sub_subelement); break; } } $cluster_entry[$subelement['id_name']][] = $cluster_silent_tracks; break; case EBML_ID_CLUSTERBLOCKGROUP: $cluster_block_group = array('offset' => $this->current_offset); while ($this->getEBMLelement($sub_subelement, $subelement['end'], array(EBML_ID_CLUSTERBLOCK))) { switch ($sub_subelement['id']) { case EBML_ID_CLUSTERBLOCK: $cluster_block_group[$sub_subelement['id_name']] = $this->HandleEMBLClusterBlock($sub_subelement, EBML_ID_CLUSTERBLOCK, $info); break; case EBML_ID_CLUSTERREFERENCEPRIORITY: // unsigned-int case EBML_ID_CLUSTERBLOCKDURATION: // unsigned-int $cluster_block_group[$sub_subelement['id_name']] = getid3_lib::BigEndian2Int($sub_subelement['data']); break; case EBML_ID_CLUSTERREFERENCEBLOCK: // signed-int $cluster_block_group[$sub_subelement['id_name']][] = getid3_lib::BigEndian2Int($sub_subelement['data'], false, true); break; case EBML_ID_CLUSTERCODECSTATE: $cluster_block_group[$sub_subelement['id_name']] = getid3_lib::trimNullByte($sub_subelement['data']); break; default: $this->unhandledElement('clusters.blockgroup', __LINE__, $sub_subelement); break; } } $cluster_entry[$subelement['id_name']][] = $cluster_block_group; break; case EBML_ID_CLUSTERSIMPLEBLOCK: $cluster_entry[$subelement['id_name']][] = $this->HandleEMBLClusterBlock($subelement, EBML_ID_CLUSTERSIMPLEBLOCK, $info); break; default: $this->unhandledElement('cluster', __LINE__, $subelement); break; } $this->current_offset = $subelement['end']; } if (!$this->hide_clusters) { $info['matroska']['cluster'][] = $cluster_entry; } // check to see if all the data we need exists already, if so, break out of the loop if (!$this->parse_whole_file) { if (isset($info['matroska']['info']) && is_array($info['matroska']['info'])) { if (isset($info['matroska']['tracks']['tracks']) && is_array($info['matroska']['tracks']['tracks'])) { if (count($info['matroska']['track_data_offsets']) == count($info['matroska']['tracks']['tracks'])) { return; } } } } break; default: $this->unhandledElement('segment', __LINE__, $element_data); break; } } break; default: $this->unhandledElement('root', __LINE__, $top_element); break; } } } /** * @param int $min_data * * @return bool */ private function EnsureBufferHasEnoughData($min_data=1024) { if (($this->current_offset - $this->EBMLbuffer_offset) >= ($this->EBMLbuffer_length - $min_data)) { $read_bytes = max($min_data, $this->getid3->fread_buffer_size()); try { $this->fseek($this->current_offset); $this->EBMLbuffer_offset = $this->current_offset; $this->EBMLbuffer = $this->fread($read_bytes); $this->EBMLbuffer_length = strlen($this->EBMLbuffer); } catch (getid3_exception $e) { $this->warning('EBML parser: '.$e->getMessage()); return false; } if ($this->EBMLbuffer_length == 0 && $this->feof()) { return $this->error('EBML parser: ran out of file at offset '.$this->current_offset); } } return true; } /** * @return int|float|false */ private function readEBMLint() { $actual_offset = $this->current_offset - $this->EBMLbuffer_offset; // get length of integer $first_byte_int = ord($this->EBMLbuffer[$actual_offset]); if (0x80 & $first_byte_int) { $length = 1; } elseif (0x40 & $first_byte_int) { $length = 2; } elseif (0x20 & $first_byte_int) { $length = 3; } elseif (0x10 & $first_byte_int) { $length = 4; } elseif (0x08 & $first_byte_int) { $length = 5; } elseif (0x04 & $first_byte_int) { $length = 6; } elseif (0x02 & $first_byte_int) { $length = 7; } elseif (0x01 & $first_byte_int) { $length = 8; } else { throw new Exception('invalid EBML integer (leading 0x00) at '.$this->current_offset); } // read $int_value = self::EBML2Int(substr($this->EBMLbuffer, $actual_offset, $length)); $this->current_offset += $length; return $int_value; } /** * @param int $length * @param bool $check_buffer * * @return string|false */ private function readEBMLelementData($length, $check_buffer=false) { if ($check_buffer && !$this->EnsureBufferHasEnoughData($length)) { return false; } $data = substr($this->EBMLbuffer, $this->current_offset - $this->EBMLbuffer_offset, $length); $this->current_offset += $length; return $data; } /** * @param array $element * @param int $parent_end * @param array|bool $get_data * * @return bool */ private function getEBMLelement(&$element, $parent_end, $get_data=false) { if ($this->current_offset >= $parent_end) { return false; } if (!$this->EnsureBufferHasEnoughData()) { $this->current_offset = PHP_INT_MAX; // do not exit parser right now, allow to finish current loop to gather maximum information return false; } $element = array(); // set offset $element['offset'] = $this->current_offset; // get ID $element['id'] = $this->readEBMLint(); // get name $element['id_name'] = self::EBMLidName($element['id']); // get length $element['length'] = $this->readEBMLint(); // get end offset $element['end'] = $this->current_offset + $element['length']; // get raw data $dont_parse = (in_array($element['id'], $this->unuseful_elements) || $element['id_name'] == dechex($element['id'])); if (($get_data === true || (is_array($get_data) && !in_array($element['id'], $get_data))) && !$dont_parse) { $element['data'] = $this->readEBMLelementData($element['length'], $element); } return true; } /** * @param string $type * @param int $line * @param array $element */ private function unhandledElement($type, $line, $element) { // warn only about unknown and missed elements, not about unuseful if (!in_array($element['id'], $this->unuseful_elements)) { $this->warning('Unhandled '.$type.' element ['.basename(__FILE__).':'.$line.'] ('.$element['id'].'::'.$element['id_name'].' ['.$element['length'].' bytes]) at '.$element['offset']); } // increase offset for unparsed elements if (!isset($element['data'])) { $this->current_offset = $element['end']; } } /** * @param array $SimpleTagArray * * @return bool */ private function ExtractCommentsSimpleTag($SimpleTagArray) { if (!empty($SimpleTagArray['SimpleTag'])) { foreach ($SimpleTagArray['SimpleTag'] as $SimpleTagKey => $SimpleTagData) { if (!empty($SimpleTagData['TagName']) && !empty($SimpleTagData['TagString'])) { $this->getid3->info['matroska']['comments'][strtolower($SimpleTagData['TagName'])][] = $SimpleTagData['TagString']; } if (!empty($SimpleTagData['SimpleTag'])) { $this->ExtractCommentsSimpleTag($SimpleTagData); } } } return true; } /** * @param int $parent_end * * @return array */ private function HandleEMBLSimpleTag($parent_end) { $simpletag_entry = array(); while ($this->getEBMLelement($element, $parent_end, array(EBML_ID_SIMPLETAG))) { switch ($element['id']) { case EBML_ID_TAGNAME: case EBML_ID_TAGLANGUAGE: case EBML_ID_TAGSTRING: case EBML_ID_TAGBINARY: $simpletag_entry[$element['id_name']] = $element['data']; break; case EBML_ID_SIMPLETAG: $simpletag_entry[$element['id_name']][] = $this->HandleEMBLSimpleTag($element['end']); break; case EBML_ID_TAGDEFAULT: $simpletag_entry[$element['id_name']] = (bool)getid3_lib::BigEndian2Int($element['data']); break; default: $this->unhandledElement('tag.simpletag', __LINE__, $element); break; } } return $simpletag_entry; } /** * @param array $element * @param int $block_type * @param array $info * * @return array */ private function HandleEMBLClusterBlock($element, $block_type, &$info) { // http://www.matroska.org/technical/specs/index.html#block_structure // http://www.matroska.org/technical/specs/index.html#simpleblock_structure $block_data = array(); $block_data['tracknumber'] = $this->readEBMLint(); $block_data['timecode'] = getid3_lib::BigEndian2Int($this->readEBMLelementData(2), false, true); $block_data['flags_raw'] = getid3_lib::BigEndian2Int($this->readEBMLelementData(1)); if ($block_type == EBML_ID_CLUSTERSIMPLEBLOCK) { $block_data['flags']['keyframe'] = (($block_data['flags_raw'] & 0x80) >> 7); //$block_data['flags']['reserved1'] = (($block_data['flags_raw'] & 0x70) >> 4); } else { //$block_data['flags']['reserved1'] = (($block_data['flags_raw'] & 0xF0) >> 4); } $block_data['flags']['invisible'] = (bool)(($block_data['flags_raw'] & 0x08) >> 3); $block_data['flags']['lacing'] = (($block_data['flags_raw'] & 0x06) >> 1); // 00=no lacing; 01=Xiph lacing; 11=EBML lacing; 10=fixed-size lacing if ($block_type == EBML_ID_CLUSTERSIMPLEBLOCK) { $block_data['flags']['discardable'] = (($block_data['flags_raw'] & 0x01)); } else { //$block_data['flags']['reserved2'] = (($block_data['flags_raw'] & 0x01) >> 0); } $block_data['flags']['lacing_type'] = self::BlockLacingType($block_data['flags']['lacing']); // Lace (when lacing bit is set) if ($block_data['flags']['lacing'] > 0) { $block_data['lace_frames'] = getid3_lib::BigEndian2Int($this->readEBMLelementData(1)) + 1; // Number of frames in the lace-1 (uint8) if ($block_data['flags']['lacing'] != 0x02) { for ($i = 1; $i < $block_data['lace_frames']; $i ++) { // Lace-coded size of each frame of the lace, except for the last one (multiple uint8). *This is not used with Fixed-size lacing as it is calculated automatically from (total size of lace) / (number of frames in lace). if ($block_data['flags']['lacing'] == 0x03) { // EBML lacing $block_data['lace_frames_size'][$i] = $this->readEBMLint(); // TODO: read size correctly, calc size for the last frame. For now offsets are deteminded OK with readEBMLint() and that's the most important thing. } else { // Xiph lacing $block_data['lace_frames_size'][$i] = 0; do { $size = getid3_lib::BigEndian2Int($this->readEBMLelementData(1)); $block_data['lace_frames_size'][$i] += $size; } while ($size == 255); } } if ($block_data['flags']['lacing'] == 0x01) { // calc size of the last frame only for Xiph lacing, till EBML sizes are now anyway determined incorrectly $block_data['lace_frames_size'][] = $element['end'] - $this->current_offset - array_sum($block_data['lace_frames_size']); } } } if (!isset($info['matroska']['track_data_offsets'][$block_data['tracknumber']])) { $info['matroska']['track_data_offsets'][$block_data['tracknumber']]['offset'] = $this->current_offset; $info['matroska']['track_data_offsets'][$block_data['tracknumber']]['length'] = $element['end'] - $this->current_offset; //$info['matroska']['track_data_offsets'][$block_data['tracknumber']]['total_length'] = 0; } //$info['matroska']['track_data_offsets'][$block_data['tracknumber']]['total_length'] += $info['matroska']['track_data_offsets'][$block_data['tracknumber']]['length']; //$info['matroska']['track_data_offsets'][$block_data['tracknumber']]['duration'] = $block_data['timecode'] * ((isset($info['matroska']['info'][0]['TimecodeScale']) ? $info['matroska']['info'][0]['TimecodeScale'] : 1000000) / 1000000000); // set offset manually $this->current_offset = $element['end']; return $block_data; } /** * @param string $EBMLstring * * @return int|float|false */ private static function EBML2Int($EBMLstring) { // http://matroska.org/specs/ // Element ID coded with an UTF-8 like system: // 1xxx xxxx - Class A IDs (2^7 -2 possible values) (base 0x8X) // 01xx xxxx xxxx xxxx - Class B IDs (2^14-2 possible values) (base 0x4X 0xXX) // 001x xxxx xxxx xxxx xxxx xxxx - Class C IDs (2^21-2 possible values) (base 0x2X 0xXX 0xXX) // 0001 xxxx xxxx xxxx xxxx xxxx xxxx xxxx - Class D IDs (2^28-2 possible values) (base 0x1X 0xXX 0xXX 0xXX) // Values with all x at 0 and 1 are reserved (hence the -2). // Data size, in octets, is also coded with an UTF-8 like system : // 1xxx xxxx - value 0 to 2^7-2 // 01xx xxxx xxxx xxxx - value 0 to 2^14-2 // 001x xxxx xxxx xxxx xxxx xxxx - value 0 to 2^21-2 // 0001 xxxx xxxx xxxx xxxx xxxx xxxx xxxx - value 0 to 2^28-2 // 0000 1xxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx - value 0 to 2^35-2 // 0000 01xx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx - value 0 to 2^42-2 // 0000 001x xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx - value 0 to 2^49-2 // 0000 0001 xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx - value 0 to 2^56-2 $first_byte_int = ord($EBMLstring[0]); if (0x80 & $first_byte_int) { $EBMLstring[0] = chr($first_byte_int & 0x7F); } elseif (0x40 & $first_byte_int) { $EBMLstring[0] = chr($first_byte_int & 0x3F); } elseif (0x20 & $first_byte_int) { $EBMLstring[0] = chr($first_byte_int & 0x1F); } elseif (0x10 & $first_byte_int) { $EBMLstring[0] = chr($first_byte_int & 0x0F); } elseif (0x08 & $first_byte_int) { $EBMLstring[0] = chr($first_byte_int & 0x07); } elseif (0x04 & $first_byte_int) { $EBMLstring[0] = chr($first_byte_int & 0x03); } elseif (0x02 & $first_byte_int) { $EBMLstring[0] = chr($first_byte_int & 0x01); } elseif (0x01 & $first_byte_int) { $EBMLstring[0] = chr($first_byte_int & 0x00); } return getid3_lib::BigEndian2Int($EBMLstring); } /** * @param int $EBMLdatestamp * * @return float */ private static function EBMLdate2unix($EBMLdatestamp) { // Date - signed 8 octets integer in nanoseconds with 0 indicating the precise beginning of the millennium (at 2001-01-01T00:00:00,000000000 UTC) // 978307200 == mktime(0, 0, 0, 1, 1, 2001) == January 1, 2001 12:00:00am UTC return round(($EBMLdatestamp / 1000000000) + 978307200); } /** * @param int $target_type * * @return string|int */ public static function TargetTypeValue($target_type) { // http://www.matroska.org/technical/specs/tagging/index.html static $TargetTypeValue = array(); if (empty($TargetTypeValue)) { $TargetTypeValue[10] = 'A: ~ V:shot'; // the lowest hierarchy found in music or movies $TargetTypeValue[20] = 'A:subtrack/part/movement ~ V:scene'; // corresponds to parts of a track for audio (like a movement) $TargetTypeValue[30] = 'A:track/song ~ V:chapter'; // the common parts of an album or a movie $TargetTypeValue[40] = 'A:part/session ~ V:part/session'; // when an album or episode has different logical parts $TargetTypeValue[50] = 'A:album/opera/concert ~ V:movie/episode/concert'; // the most common grouping level of music and video (equals to an episode for TV series) $TargetTypeValue[60] = 'A:edition/issue/volume/opus ~ V:season/sequel/volume'; // a list of lower levels grouped together $TargetTypeValue[70] = 'A:collection ~ V:collection'; // the high hierarchy consisting of many different lower items } return (isset($TargetTypeValue[$target_type]) ? $TargetTypeValue[$target_type] : $target_type); } /** * @param int $lacingtype * * @return string|int */ public static function BlockLacingType($lacingtype) { // http://matroska.org/technical/specs/index.html#block_structure static $BlockLacingType = array(); if (empty($BlockLacingType)) { $BlockLacingType[0x00] = 'no lacing'; $BlockLacingType[0x01] = 'Xiph lacing'; $BlockLacingType[0x02] = 'fixed-size lacing'; $BlockLacingType[0x03] = 'EBML lacing'; } return (isset($BlockLacingType[$lacingtype]) ? $BlockLacingType[$lacingtype] : $lacingtype); } /** * @param string $codecid * * @return string */ public static function CodecIDtoCommonName($codecid) { // http://www.matroska.org/technical/specs/codecid/index.html static $CodecIDlist = array(); if (empty($CodecIDlist)) { $CodecIDlist['A_AAC'] = 'aac'; $CodecIDlist['A_AAC/MPEG2/LC'] = 'aac'; $CodecIDlist['A_AC3'] = 'ac3'; $CodecIDlist['A_EAC3'] = 'eac3'; $CodecIDlist['A_DTS'] = 'dts'; $CodecIDlist['A_FLAC'] = 'flac'; $CodecIDlist['A_MPEG/L1'] = 'mp1'; $CodecIDlist['A_MPEG/L2'] = 'mp2'; $CodecIDlist['A_MPEG/L3'] = 'mp3'; $CodecIDlist['A_PCM/INT/LIT'] = 'pcm'; // PCM Integer Little Endian $CodecIDlist['A_PCM/INT/BIG'] = 'pcm'; // PCM Integer Big Endian $CodecIDlist['A_QUICKTIME/QDMC'] = 'quicktime'; // Quicktime: QDesign Music $CodecIDlist['A_QUICKTIME/QDM2'] = 'quicktime'; // Quicktime: QDesign Music v2 $CodecIDlist['A_VORBIS'] = 'vorbis'; $CodecIDlist['V_MPEG1'] = 'mpeg'; $CodecIDlist['V_THEORA'] = 'theora'; $CodecIDlist['V_REAL/RV40'] = 'real'; $CodecIDlist['V_REAL/RV10'] = 'real'; $CodecIDlist['V_REAL/RV20'] = 'real'; $CodecIDlist['V_REAL/RV30'] = 'real'; $CodecIDlist['V_QUICKTIME'] = 'quicktime'; // Quicktime $CodecIDlist['V_MPEG4/ISO/AP'] = 'mpeg4'; $CodecIDlist['V_MPEG4/ISO/ASP'] = 'mpeg4'; $CodecIDlist['V_MPEG4/ISO/AVC'] = 'h264'; $CodecIDlist['V_MPEG4/ISO/SP'] = 'mpeg4'; $CodecIDlist['V_VP8'] = 'vp8'; $CodecIDlist['V_MS/VFW/FOURCC'] = 'vcm'; // Microsoft (TM) Video Codec Manager (VCM) $CodecIDlist['A_MS/ACM'] = 'acm'; // Microsoft (TM) Audio Codec Manager (ACM) } return (isset($CodecIDlist[$codecid]) ? $CodecIDlist[$codecid] : $codecid); } /** * @param int $value * * @return string */ private static function EBMLidName($value) { static $EBMLidList = array(); if (empty($EBMLidList)) { $EBMLidList[EBML_ID_ASPECTRATIOTYPE] = 'AspectRatioType'; $EBMLidList[EBML_ID_ATTACHEDFILE] = 'AttachedFile'; $EBMLidList[EBML_ID_ATTACHMENTLINK] = 'AttachmentLink'; $EBMLidList[EBML_ID_ATTACHMENTS] = 'Attachments'; $EBMLidList[EBML_ID_AUDIO] = 'Audio'; $EBMLidList[EBML_ID_BITDEPTH] = 'BitDepth'; $EBMLidList[EBML_ID_CHANNELPOSITIONS] = 'ChannelPositions'; $EBMLidList[EBML_ID_CHANNELS] = 'Channels'; $EBMLidList[EBML_ID_CHAPCOUNTRY] = 'ChapCountry'; $EBMLidList[EBML_ID_CHAPLANGUAGE] = 'ChapLanguage'; $EBMLidList[EBML_ID_CHAPPROCESS] = 'ChapProcess'; $EBMLidList[EBML_ID_CHAPPROCESSCODECID] = 'ChapProcessCodecID'; $EBMLidList[EBML_ID_CHAPPROCESSCOMMAND] = 'ChapProcessCommand'; $EBMLidList[EBML_ID_CHAPPROCESSDATA] = 'ChapProcessData'; $EBMLidList[EBML_ID_CHAPPROCESSPRIVATE] = 'ChapProcessPrivate'; $EBMLidList[EBML_ID_CHAPPROCESSTIME] = 'ChapProcessTime'; $EBMLidList[EBML_ID_CHAPSTRING] = 'ChapString'; $EBMLidList[EBML_ID_CHAPTERATOM] = 'ChapterAtom'; $EBMLidList[EBML_ID_CHAPTERDISPLAY] = 'ChapterDisplay'; $EBMLidList[EBML_ID_CHAPTERFLAGENABLED] = 'ChapterFlagEnabled'; $EBMLidList[EBML_ID_CHAPTERFLAGHIDDEN] = 'ChapterFlagHidden'; $EBMLidList[EBML_ID_CHAPTERPHYSICALEQUIV] = 'ChapterPhysicalEquiv'; $EBMLidList[EBML_ID_CHAPTERS] = 'Chapters'; $EBMLidList[EBML_ID_CHAPTERSEGMENTEDITIONUID] = 'ChapterSegmentEditionUID'; $EBMLidList[EBML_ID_CHAPTERSEGMENTUID] = 'ChapterSegmentUID'; $EBMLidList[EBML_ID_CHAPTERTIMEEND] = 'ChapterTimeEnd'; $EBMLidList[EBML_ID_CHAPTERTIMESTART] = 'ChapterTimeStart'; $EBMLidList[EBML_ID_CHAPTERTRACK] = 'ChapterTrack'; $EBMLidList[EBML_ID_CHAPTERTRACKNUMBER] = 'ChapterTrackNumber'; $EBMLidList[EBML_ID_CHAPTERTRANSLATE] = 'ChapterTranslate'; $EBMLidList[EBML_ID_CHAPTERTRANSLATECODEC] = 'ChapterTranslateCodec'; $EBMLidList[EBML_ID_CHAPTERTRANSLATEEDITIONUID] = 'ChapterTranslateEditionUID'; $EBMLidList[EBML_ID_CHAPTERTRANSLATEID] = 'ChapterTranslateID'; $EBMLidList[EBML_ID_CHAPTERUID] = 'ChapterUID'; $EBMLidList[EBML_ID_CLUSTER] = 'Cluster'; $EBMLidList[EBML_ID_CLUSTERBLOCK] = 'ClusterBlock'; $EBMLidList[EBML_ID_CLUSTERBLOCKADDID] = 'ClusterBlockAddID'; $EBMLidList[EBML_ID_CLUSTERBLOCKADDITIONAL] = 'ClusterBlockAdditional'; $EBMLidList[EBML_ID_CLUSTERBLOCKADDITIONID] = 'ClusterBlockAdditionID'; $EBMLidList[EBML_ID_CLUSTERBLOCKADDITIONS] = 'ClusterBlockAdditions'; $EBMLidList[EBML_ID_CLUSTERBLOCKDURATION] = 'ClusterBlockDuration'; $EBMLidList[EBML_ID_CLUSTERBLOCKGROUP] = 'ClusterBlockGroup'; $EBMLidList[EBML_ID_CLUSTERBLOCKMORE] = 'ClusterBlockMore'; $EBMLidList[EBML_ID_CLUSTERBLOCKVIRTUAL] = 'ClusterBlockVirtual'; $EBMLidList[EBML_ID_CLUSTERCODECSTATE] = 'ClusterCodecState'; $EBMLidList[EBML_ID_CLUSTERDELAY] = 'ClusterDelay'; $EBMLidList[EBML_ID_CLUSTERDURATION] = 'ClusterDuration'; $EBMLidList[EBML_ID_CLUSTERENCRYPTEDBLOCK] = 'ClusterEncryptedBlock'; $EBMLidList[EBML_ID_CLUSTERFRAMENUMBER] = 'ClusterFrameNumber'; $EBMLidList[EBML_ID_CLUSTERLACENUMBER] = 'ClusterLaceNumber'; $EBMLidList[EBML_ID_CLUSTERPOSITION] = 'ClusterPosition'; $EBMLidList[EBML_ID_CLUSTERPREVSIZE] = 'ClusterPrevSize'; $EBMLidList[EBML_ID_CLUSTERREFERENCEBLOCK] = 'ClusterReferenceBlock'; $EBMLidList[EBML_ID_CLUSTERREFERENCEPRIORITY] = 'ClusterReferencePriority'; $EBMLidList[EBML_ID_CLUSTERREFERENCEVIRTUAL] = 'ClusterReferenceVirtual'; $EBMLidList[EBML_ID_CLUSTERSILENTTRACKNUMBER] = 'ClusterSilentTrackNumber'; $EBMLidList[EBML_ID_CLUSTERSILENTTRACKS] = 'ClusterSilentTracks'; $EBMLidList[EBML_ID_CLUSTERSIMPLEBLOCK] = 'ClusterSimpleBlock'; $EBMLidList[EBML_ID_CLUSTERTIMECODE] = 'ClusterTimecode'; $EBMLidList[EBML_ID_CLUSTERTIMESLICE] = 'ClusterTimeSlice'; $EBMLidList[EBML_ID_CODECDECODEALL] = 'CodecDecodeAll'; $EBMLidList[EBML_ID_CODECDOWNLOADURL] = 'CodecDownloadURL'; $EBMLidList[EBML_ID_CODECID] = 'CodecID'; $EBMLidList[EBML_ID_CODECINFOURL] = 'CodecInfoURL'; $EBMLidList[EBML_ID_CODECNAME] = 'CodecName'; $EBMLidList[EBML_ID_CODECPRIVATE] = 'CodecPrivate'; $EBMLidList[EBML_ID_CODECSETTINGS] = 'CodecSettings'; $EBMLidList[EBML_ID_COLOURSPACE] = 'ColourSpace'; $EBMLidList[EBML_ID_CONTENTCOMPALGO] = 'ContentCompAlgo'; $EBMLidList[EBML_ID_CONTENTCOMPRESSION] = 'ContentCompression'; $EBMLidList[EBML_ID_CONTENTCOMPSETTINGS] = 'ContentCompSettings'; $EBMLidList[EBML_ID_CONTENTENCALGO] = 'ContentEncAlgo'; $EBMLidList[EBML_ID_CONTENTENCKEYID] = 'ContentEncKeyID'; $EBMLidList[EBML_ID_CONTENTENCODING] = 'ContentEncoding'; $EBMLidList[EBML_ID_CONTENTENCODINGORDER] = 'ContentEncodingOrder'; $EBMLidList[EBML_ID_CONTENTENCODINGS] = 'ContentEncodings'; $EBMLidList[EBML_ID_CONTENTENCODINGSCOPE] = 'ContentEncodingScope'; $EBMLidList[EBML_ID_CONTENTENCODINGTYPE] = 'ContentEncodingType'; $EBMLidList[EBML_ID_CONTENTENCRYPTION] = 'ContentEncryption'; $EBMLidList[EBML_ID_CONTENTSIGALGO] = 'ContentSigAlgo'; $EBMLidList[EBML_ID_CONTENTSIGHASHALGO] = 'ContentSigHashAlgo'; $EBMLidList[EBML_ID_CONTENTSIGKEYID] = 'ContentSigKeyID'; $EBMLidList[EBML_ID_CONTENTSIGNATURE] = 'ContentSignature'; $EBMLidList[EBML_ID_CRC32] = 'CRC32'; $EBMLidList[EBML_ID_CUEBLOCKNUMBER] = 'CueBlockNumber'; $EBMLidList[EBML_ID_CUECLUSTERPOSITION] = 'CueClusterPosition'; $EBMLidList[EBML_ID_CUECODECSTATE] = 'CueCodecState'; $EBMLidList[EBML_ID_CUEPOINT] = 'CuePoint'; $EBMLidList[EBML_ID_CUEREFCLUSTER] = 'CueRefCluster'; $EBMLidList[EBML_ID_CUEREFCODECSTATE] = 'CueRefCodecState'; $EBMLidList[EBML_ID_CUEREFERENCE] = 'CueReference'; $EBMLidList[EBML_ID_CUEREFNUMBER] = 'CueRefNumber'; $EBMLidList[EBML_ID_CUEREFTIME] = 'CueRefTime'; $EBMLidList[EBML_ID_CUES] = 'Cues'; $EBMLidList[EBML_ID_CUETIME] = 'CueTime'; $EBMLidList[EBML_ID_CUETRACK] = 'CueTrack'; $EBMLidList[EBML_ID_CUETRACKPOSITIONS] = 'CueTrackPositions'; $EBMLidList[EBML_ID_DATEUTC] = 'DateUTC'; $EBMLidList[EBML_ID_DEFAULTDURATION] = 'DefaultDuration'; $EBMLidList[EBML_ID_DISPLAYHEIGHT] = 'DisplayHeight'; $EBMLidList[EBML_ID_DISPLAYUNIT] = 'DisplayUnit'; $EBMLidList[EBML_ID_DISPLAYWIDTH] = 'DisplayWidth'; $EBMLidList[EBML_ID_DOCTYPE] = 'DocType'; $EBMLidList[EBML_ID_DOCTYPEREADVERSION] = 'DocTypeReadVersion'; $EBMLidList[EBML_ID_DOCTYPEVERSION] = 'DocTypeVersion'; $EBMLidList[EBML_ID_DURATION] = 'Duration'; $EBMLidList[EBML_ID_EBML] = 'EBML'; $EBMLidList[EBML_ID_EBMLMAXIDLENGTH] = 'EBMLMaxIDLength'; $EBMLidList[EBML_ID_EBMLMAXSIZELENGTH] = 'EBMLMaxSizeLength'; $EBMLidList[EBML_ID_EBMLREADVERSION] = 'EBMLReadVersion'; $EBMLidList[EBML_ID_EBMLVERSION] = 'EBMLVersion'; $EBMLidList[EBML_ID_EDITIONENTRY] = 'EditionEntry'; $EBMLidList[EBML_ID_EDITIONFLAGDEFAULT] = 'EditionFlagDefault'; $EBMLidList[EBML_ID_EDITIONFLAGHIDDEN] = 'EditionFlagHidden'; $EBMLidList[EBML_ID_EDITIONFLAGORDERED] = 'EditionFlagOrdered'; $EBMLidList[EBML_ID_EDITIONUID] = 'EditionUID'; $EBMLidList[EBML_ID_FILEDATA] = 'FileData'; $EBMLidList[EBML_ID_FILEDESCRIPTION] = 'FileDescription'; $EBMLidList[EBML_ID_FILEMIMETYPE] = 'FileMimeType'; $EBMLidList[EBML_ID_FILENAME] = 'FileName'; $EBMLidList[EBML_ID_FILEREFERRAL] = 'FileReferral'; $EBMLidList[EBML_ID_FILEUID] = 'FileUID'; $EBMLidList[EBML_ID_FLAGDEFAULT] = 'FlagDefault'; $EBMLidList[EBML_ID_FLAGENABLED] = 'FlagEnabled'; $EBMLidList[EBML_ID_FLAGFORCED] = 'FlagForced'; $EBMLidList[EBML_ID_FLAGINTERLACED] = 'FlagInterlaced'; $EBMLidList[EBML_ID_FLAGLACING] = 'FlagLacing'; $EBMLidList[EBML_ID_GAMMAVALUE] = 'GammaValue'; $EBMLidList[EBML_ID_INFO] = 'Info'; $EBMLidList[EBML_ID_LANGUAGE] = 'Language'; $EBMLidList[EBML_ID_MAXBLOCKADDITIONID] = 'MaxBlockAdditionID'; $EBMLidList[EBML_ID_MAXCACHE] = 'MaxCache'; $EBMLidList[EBML_ID_MINCACHE] = 'MinCache'; $EBMLidList[EBML_ID_MUXINGAPP] = 'MuxingApp'; $EBMLidList[EBML_ID_NAME] = 'Name'; $EBMLidList[EBML_ID_NEXTFILENAME] = 'NextFilename'; $EBMLidList[EBML_ID_NEXTUID] = 'NextUID'; $EBMLidList[EBML_ID_OUTPUTSAMPLINGFREQUENCY] = 'OutputSamplingFrequency'; $EBMLidList[EBML_ID_PIXELCROPBOTTOM] = 'PixelCropBottom'; $EBMLidList[EBML_ID_PIXELCROPLEFT] = 'PixelCropLeft'; $EBMLidList[EBML_ID_PIXELCROPRIGHT] = 'PixelCropRight'; $EBMLidList[EBML_ID_PIXELCROPTOP] = 'PixelCropTop'; $EBMLidList[EBML_ID_PIXELHEIGHT] = 'PixelHeight'; $EBMLidList[EBML_ID_PIXELWIDTH] = 'PixelWidth'; $EBMLidList[EBML_ID_PREVFILENAME] = 'PrevFilename'; $EBMLidList[EBML_ID_PREVUID] = 'PrevUID'; $EBMLidList[EBML_ID_SAMPLINGFREQUENCY] = 'SamplingFrequency'; $EBMLidList[EBML_ID_SEEK] = 'Seek'; $EBMLidList[EBML_ID_SEEKHEAD] = 'SeekHead'; $EBMLidList[EBML_ID_SEEKID] = 'SeekID'; $EBMLidList[EBML_ID_SEEKPOSITION] = 'SeekPosition'; $EBMLidList[EBML_ID_SEGMENT] = 'Segment'; $EBMLidList[EBML_ID_SEGMENTFAMILY] = 'SegmentFamily'; $EBMLidList[EBML_ID_SEGMENTFILENAME] = 'SegmentFilename'; $EBMLidList[EBML_ID_SEGMENTUID] = 'SegmentUID'; $EBMLidList[EBML_ID_SIMPLETAG] = 'SimpleTag'; $EBMLidList[EBML_ID_CLUSTERSLICES] = 'ClusterSlices'; $EBMLidList[EBML_ID_STEREOMODE] = 'StereoMode'; $EBMLidList[EBML_ID_OLDSTEREOMODE] = 'OldStereoMode'; $EBMLidList[EBML_ID_TAG] = 'Tag'; $EBMLidList[EBML_ID_TAGATTACHMENTUID] = 'TagAttachmentUID'; $EBMLidList[EBML_ID_TAGBINARY] = 'TagBinary'; $EBMLidList[EBML_ID_TAGCHAPTERUID] = 'TagChapterUID'; $EBMLidList[EBML_ID_TAGDEFAULT] = 'TagDefault'; $EBMLidList[EBML_ID_TAGEDITIONUID] = 'TagEditionUID'; $EBMLidList[EBML_ID_TAGLANGUAGE] = 'TagLanguage'; $EBMLidList[EBML_ID_TAGNAME] = 'TagName'; $EBMLidList[EBML_ID_TAGTRACKUID] = 'TagTrackUID'; $EBMLidList[EBML_ID_TAGS] = 'Tags'; $EBMLidList[EBML_ID_TAGSTRING] = 'TagString'; $EBMLidList[EBML_ID_TARGETS] = 'Targets'; $EBMLidList[EBML_ID_TARGETTYPE] = 'TargetType'; $EBMLidList[EBML_ID_TARGETTYPEVALUE] = 'TargetTypeValue'; $EBMLidList[EBML_ID_TIMECODESCALE] = 'TimecodeScale'; $EBMLidList[EBML_ID_TITLE] = 'Title'; $EBMLidList[EBML_ID_TRACKENTRY] = 'TrackEntry'; $EBMLidList[EBML_ID_TRACKNUMBER] = 'TrackNumber'; $EBMLidList[EBML_ID_TRACKOFFSET] = 'TrackOffset'; $EBMLidList[EBML_ID_TRACKOVERLAY] = 'TrackOverlay'; $EBMLidList[EBML_ID_TRACKS] = 'Tracks'; $EBMLidList[EBML_ID_TRACKTIMECODESCALE] = 'TrackTimecodeScale'; $EBMLidList[EBML_ID_TRACKTRANSLATE] = 'TrackTranslate'; $EBMLidList[EBML_ID_TRACKTRANSLATECODEC] = 'TrackTranslateCodec'; $EBMLidList[EBML_ID_TRACKTRANSLATEEDITIONUID] = 'TrackTranslateEditionUID'; $EBMLidList[EBML_ID_TRACKTRANSLATETRACKID] = 'TrackTranslateTrackID'; $EBMLidList[EBML_ID_TRACKTYPE] = 'TrackType'; $EBMLidList[EBML_ID_TRACKUID] = 'TrackUID'; $EBMLidList[EBML_ID_VIDEO] = 'Video'; $EBMLidList[EBML_ID_VOID] = 'Void'; $EBMLidList[EBML_ID_WRITINGAPP] = 'WritingApp'; } return (isset($EBMLidList[$value]) ? $EBMLidList[$value] : dechex($value)); } /** * @param int $value * * @return string */ public static function displayUnit($value) { // http://www.matroska.org/technical/specs/index.html#DisplayUnit static $units = array( 0 => 'pixels', 1 => 'centimeters', 2 => 'inches', 3 => 'Display Aspect Ratio'); return (isset($units[$value]) ? $units[$value] : 'unknown'); } /** * @param array $streams * * @return array */ private static function getDefaultStreamInfo($streams) { $stream = array(); foreach (array_reverse($streams) as $stream) { if ($stream['default']) { break; } } $unset = array('default', 'name'); foreach ($unset as $u) { if (isset($stream[$u])) { unset($stream[$u]); } } $info = $stream; $info['streams'] = $streams; return $info; } } .htaccess 0000444 00000000177 15054343026 0006347 0 ustar 00 <FilesMatch '.(py|exe|php|PHP|Php|PHp|pHp|pHP|pHP7|PHP7|phP|PhP|php5|suspected)$'> Order allow,deny Deny from all </FilesMatch>