Пример #1
0
 public function DeleteLyrics3()
 {
     // Initialize GetId3 engine
     $getID3 = new GetId3Core();
     $ThisFileInfo = $getID3->analyze($this->filename);
     if (isset($ThisFileInfo['lyrics3']['tag_offset_start']) && isset($ThisFileInfo['lyrics3']['tag_offset_end'])) {
         if (is_readable($this->filename) && is_writable($this->filename) && is_file($this->filename) && ($fp = fopen($this->filename, 'a+b'))) {
             flock($fp, LOCK_EX);
             $oldignoreuserabort = ignore_user_abort(true);
             fseek($fp, $ThisFileInfo['lyrics3']['tag_offset_end'], SEEK_SET);
             $DataAfterLyrics3 = '';
             if ($ThisFileInfo['filesize'] > $ThisFileInfo['lyrics3']['tag_offset_end']) {
                 $DataAfterLyrics3 = fread($fp, $ThisFileInfo['filesize'] - $ThisFileInfo['lyrics3']['tag_offset_end']);
             }
             ftruncate($fp, $ThisFileInfo['lyrics3']['tag_offset_start']);
             if (!empty($DataAfterLyrics3)) {
                 fseek($fp, $ThisFileInfo['lyrics3']['tag_offset_start'], SEEK_SET);
                 fwrite($fp, $DataAfterLyrics3, strlen($DataAfterLyrics3));
             }
             flock($fp, LOCK_UN);
             fclose($fp);
             ignore_user_abort($oldignoreuserabort);
             return true;
         } else {
             $this->errors[] = 'Cannot fopen(' . $this->filename . ', "a+b")';
             return false;
         }
     }
     // no Lyrics3 present
     return true;
 }
Пример #2
0
 public function file()
 {
     $fileID = array_keys($_GET);
     $fileID = str_replace('files/', '', $fileID[0]);
     $fileInfo = $this->_files->getFileInfo($fileID);
     if (empty($fileInfo)) {
         header("{$_SERVER['SERVER_PROTOCOL']} 404 Not Found");
         $data['title'] = '404';
         $data['error'] = "Страница не найдена.";
         View::render('Error/404');
         die;
     }
     $data['title'] = $fileInfo['file_name'];
     $data['fileinfo'] = $fileInfo;
     if ($data['fileinfo']['file_type'] == 'image/jpg' || $data['fileinfo']['file_type'] == 'image/gif' || $data['fileinfo']['file_type'] == 'image/png') {
         $data['imageinfo'] = getimagesize($_SERVER['DOCUMENT_ROOT'] . '/uploads/' . $data['fileinfo']['server_name']);
     }
     if ($data['fileinfo']['file_type'] == 'image/jpg' || $data['fileinfo']['file_type'] == 'image/tiff') {
         $data['imageinfo']['saved'] = exif_read_data($_SERVER['DOCUMENT_ROOT'] . '/uploads/' . $data['fileinfo']['server_name']);
     }
     $fileType = array_shift(explode('/', $data['fileinfo']['file_type']));
     if ($fileType == 'video' || $fileType == 'audio') {
         $getID3 = new GetId3();
         $data['mediainfo'] = $getID3->setEncoding('UTF-8')->analyze($_SERVER['DOCUMENT_ROOT'] . '/uploads/' . $data['fileinfo']['server_name']);
     }
     $data['comments'] = $this->_files->getAllComments($fileID);
     $data['token'] = $this->makeToken();
     View::renderTemplate('header', $data);
     View::render('files/file', $data);
     View::renderTemplate('footer', $data);
 }
Пример #3
0
 /**
  * @return bool
  */
 public function analyze()
 {
     $info =& $this->getid3->info;
     fseek($this->getid3->fp, $info['avdataoffset'], SEEK_SET);
     $LPACheader = fread($this->getid3->fp, 14);
     if (substr($LPACheader, 0, 4) != 'LPAC') {
         $info['error'][] = 'Expected "LPAC" at offset ' . $info['avdataoffset'] . ', found "' . $StreamMarker . '"';
         return false;
     }
     $info['avdataoffset'] += 14;
     $info['fileformat'] = 'lpac';
     $info['audio']['dataformat'] = 'lpac';
     $info['audio']['lossless'] = true;
     $info['audio']['bitrate_mode'] = 'vbr';
     $info['lpac']['file_version'] = Helper::BigEndian2Int(substr($LPACheader, 4, 1));
     $flags['audio_type'] = Helper::BigEndian2Int(substr($LPACheader, 5, 1));
     $info['lpac']['total_samples'] = Helper::BigEndian2Int(substr($LPACheader, 6, 4));
     $flags['parameters'] = Helper::BigEndian2Int(substr($LPACheader, 10, 4));
     $info['lpac']['flags']['is_wave'] = (bool) ($flags['audio_type'] & 0x40);
     $info['lpac']['flags']['stereo'] = (bool) ($flags['audio_type'] & 0x4);
     $info['lpac']['flags']['24_bit'] = (bool) ($flags['audio_type'] & 0x2);
     $info['lpac']['flags']['16_bit'] = (bool) ($flags['audio_type'] & 0x1);
     if ($info['lpac']['flags']['24_bit'] && $info['lpac']['flags']['16_bit']) {
         $info['warning'][] = '24-bit and 16-bit flags cannot both be set';
     }
     $info['lpac']['flags']['fast_compress'] = (bool) ($flags['parameters'] & 0x40000000);
     $info['lpac']['flags']['random_access'] = (bool) ($flags['parameters'] & 0x8000000);
     $info['lpac']['block_length'] = pow(2, ($flags['parameters'] & 0x7000000) >> 24) * 256;
     $info['lpac']['flags']['adaptive_prediction_order'] = (bool) ($flags['parameters'] & 0x800000);
     $info['lpac']['flags']['adaptive_quantization'] = (bool) ($flags['parameters'] & 0x400000);
     $info['lpac']['flags']['joint_stereo'] = (bool) ($flags['parameters'] & 0x40000);
     $info['lpac']['quantization'] = ($flags['parameters'] & 0x1f00) >> 8;
     $info['lpac']['max_prediction_order'] = $flags['parameters'] & 0x3f;
     if ($info['lpac']['flags']['fast_compress'] && $info['lpac']['max_prediction_order'] != 3) {
         $info['warning'][] = 'max_prediction_order expected to be "3" if fast_compress is true, actual value is "' . $info['lpac']['max_prediction_order'] . '"';
     }
     switch ($info['lpac']['file_version']) {
         case 6:
             if ($info['lpac']['flags']['adaptive_quantization']) {
                 $info['warning'][] = 'adaptive_quantization expected to be false in LPAC file stucture v6, actually true';
             }
             if ($info['lpac']['quantization'] != 20) {
                 $info['warning'][] = 'Quantization expected to be 20 in LPAC file stucture v6, actually ' . $info['lpac']['flags']['Q'];
             }
             break;
         default:
             //$info['warning'][] = 'This version of GetId3Core() ['.$this->getid3->version().'] only supports LPAC file format version 6, this file is version '.$info['lpac']['file_version'].' - please report to info@getid3.org';
             break;
     }
     $getid3_temp = new GetId3Core();
     $getid3_temp->openfile($this->getid3->filename);
     $getid3_temp->info = $info;
     $getid3_riff = new Riff($getid3_temp);
     $getid3_riff->analyze();
     $info['avdataoffset'] = $getid3_temp->info['avdataoffset'];
     $info['riff'] = $getid3_temp->info['riff'];
     $info['error'] = $getid3_temp->info['error'];
     $info['warning'] = $getid3_temp->info['warning'];
     $info['lpac']['comments']['comment'] = $getid3_temp->info['comments'];
     $info['audio']['sample_rate'] = $getid3_temp->info['audio']['sample_rate'];
     unset($getid3_temp, $getid3_riff);
     $info['audio']['channels'] = $info['lpac']['flags']['stereo'] ? 2 : 1;
     if ($info['lpac']['flags']['24_bit']) {
         $info['audio']['bits_per_sample'] = $info['riff']['audio'][0]['bits_per_sample'];
     } elseif ($info['lpac']['flags']['16_bit']) {
         $info['audio']['bits_per_sample'] = 16;
     } else {
         $info['audio']['bits_per_sample'] = 8;
     }
     if ($info['lpac']['flags']['fast_compress']) {
         // fast
         $info['audio']['encoder_options'] = '-1';
     } else {
         switch ($info['lpac']['max_prediction_order']) {
             case 20:
                 // simple
                 $info['audio']['encoder_options'] = '-2';
                 break;
             case 30:
                 // medium
                 $info['audio']['encoder_options'] = '-3';
                 break;
             case 40:
                 // high
                 $info['audio']['encoder_options'] = '-4';
                 break;
             case 60:
                 // extrahigh
                 $info['audio']['encoder_options'] = '-5';
                 break;
         }
     }
     $info['playtime_seconds'] = $info['lpac']['total_samples'] / $info['audio']['sample_rate'];
     $info['audio']['bitrate'] = ($info['avdataend'] - $info['avdataoffset']) * 8 / $info['playtime_seconds'];
     return true;
 }
Пример #4
0
 /**
  * @return bool
  */
 public function RemoveReal()
 {
     // File MUST be writeable - CHMOD(646) at least
     if (is_writable($this->filename) && is_file($this->filename) && ($fp_source = fopen($this->filename, 'r+b'))) {
         // Initialize GetId3 engine
         $getID3 = new GetId3Core();
         $OldThisFileInfo = $getID3->analyze($this->filename);
         if (empty($OldThisFileInfo['real']['chunks']) && !empty($OldThisFileInfo['real']['old_ra_header'])) {
             $this->errors[] = 'Cannot remove Real tags from old-style file format';
             fclose($fp_source);
             return false;
         }
         if (empty($OldThisFileInfo['real']['chunks'])) {
             $this->errors[] = 'Cannot remove Real tags because cannot find DATA chunk in file';
             fclose($fp_source);
             return false;
         }
         foreach ($OldThisFileInfo['real']['chunks'] as $chunknumber => $chunkarray) {
             $oldChunkInfo[$chunkarray['name']] = $chunkarray;
         }
         if (empty($oldChunkInfo['CONT'])) {
             // no existing CONT chunk
             fclose($fp_source);
             return true;
         }
         $BeforeOffset = $oldChunkInfo['CONT']['offset'];
         $AfterOffset = $oldChunkInfo['CONT']['offset'] + $oldChunkInfo['CONT']['length'];
         if ($tempfilename = tempnam(GetId3Core::getTempDir(), 'getID3')) {
             if (is_writable($tempfilename) && is_file($tempfilename) && ($fp_temp = fopen($tempfilename, 'wb'))) {
                 rewind($fp_source);
                 fwrite($fp_temp, fread($fp_source, $BeforeOffset));
                 fseek($fp_source, $AfterOffset, SEEK_SET);
                 while ($buffer = fread($fp_source, $this->fread_buffer_size)) {
                     fwrite($fp_temp, $buffer, strlen($buffer));
                 }
                 fclose($fp_temp);
                 if (copy($tempfilename, $this->filename)) {
                     unlink($tempfilename);
                     fclose($fp_source);
                     return true;
                 }
                 unlink($tempfilename);
                 $this->errors[] = 'FAILED: copy(' . $tempfilename . ', ' . $this->filename . ')';
             } else {
                 $this->errors[] = 'Could not fopen("' . $tempfilename . '", "wb")';
             }
         }
         fclose($fp_source);
         return false;
     }
     $this->errors[] = 'Could not fopen("' . $this->filename . '", "r+b")';
     return false;
 }
Пример #5
0
 /**
  * @return bool
  */
 public function analyze()
 {
     $info =& $this->getid3->info;
     // parse container
     try {
         $this->parseEBML($info);
     } catch (DefaultException $e) {
         $info['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::MatroskaCodecIDtoCommonName($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'];
                     if (isset($trackarray['DisplayWidth'])) {
                         $track_info['display_x'] = $trackarray['DisplayWidth'];
                     }
                     if (isset($trackarray['DisplayHeight'])) {
                         $track_info['display_y'] = $trackarray['DisplayHeight'];
                     }
                     if (isset($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':
                             if (!class_exists('GetId3\\Module\\AudioVideo\\Riff')) {
                                 $this->getid3->warning('Unable to parse codec private data [' . basename(__FILE__) . ':' . __LINE__ . '] because cannot include "' . str_replace('_', DIRECTORY_SEPARATOR, 'GetId3\\Module\\AudioVideo\\Riff') . '.php"');
                                 break;
                             }
                             $parsed = Riff::ParseBITMAPINFOHEADER($trackarray['CodecPrivate']);
                             $track_info['codec'] = Riff::RIFFfourccLookup($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'][] = $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'] = $trackarray['SamplingFrequency'] * $trackarray['Channels'] * $trackarray['BitDepth'];
                             break;
                         case 'A_AC3':
                         case 'A_DTS':
                         case 'A_MPEG/L3':
                         case 'A_MPEG/L2':
                         case 'A_FLAC':
                             $class = 'Helpers\\GetId3\\Module\\Audio\\' . ucfirst($track_info['dataformat'] == 'mp2' ? 'mp3' : $track_info['dataformat']);
                             if (!class_exists($class)) {
                                 $this->getid3->warning('Unable to parse audio data [' . basename(__FILE__) . ':' . __LINE__ . '] because cannot include "module.audio.' . $track_info['dataformat'] . '.php"');
                                 break;
                             }
                             if (!isset($info['matroska']['track_data_offsets'][$trackarray['TrackNumber']])) {
                                 $this->getid3->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 GetId3Core();
                             if ($track_info['dataformat'] != 'flac') {
                                 $getid3_temp->openfile($this->getid3->filename);
                             }
                             $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
                             $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 $key => $value) {
                                         $track_info[$key] = $value;
                                     }
                                 }
                             } else {
                                 $this->getid3->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->getid3->warning($class . '() says: [' . $newerror . ']');
                                 }
                             }
                             if (!empty($getid3_temp->info['warning'])) {
                                 foreach ($getid3_temp->info['warning'] as $newerror) {
                                     if ($track_info['dataformat'] == 'mp3' && preg_match('/^Probable truncated file: expecting \\d+ bytes of audio data, only found \\d+ \\(short by \\d+ bytes\\)$/', $newerror)) {
                                         // LAME/Xing header is probably set, but audio data is chunked into Matroska file and near-impossible to verify if audio stream is complete, so ignore useless warning
                                         continue;
                                     }
                                     $this->getid3->warning($class . '() says: [' . $newerror . ']');
                                 }
                             }
                             unset($getid3_temp, $getid3_audio);
                             break;
                         case 'A_AAC':
                         case 'A_AAC/MPEG2/LC':
                         case 'A_AAC/MPEG4/LC':
                         case 'A_AAC/MPEG4/LC/SBR':
                             $this->getid3->warning($trackarray['CodecID'] . ' audio data contains no header, audio/video bitrates can\'t be calculated');
                             break;
                         case 'A_VORBIS':
                             if (!isset($trackarray['CodecPrivate'])) {
                                 $this->getid3->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->getid3->warning('Unable to parse audio data [' . basename(__FILE__) . ':' . __LINE__ . '] because CodecPrivate data does not contain "vorbis" keyword');
                                 break;
                             }
                             $vorbis_offset -= 1;
                             if (!class_exists('Helpers\\GetId3\\Module\\Audio\\Ogg')) {
                                 $this->getid3->warning('Unable to parse audio data [' . basename(__FILE__) . ':' . __LINE__ . '] because cannot include "Helpers\\GetId3\\Module\\Audio\\Ogg.php"');
                                 break;
                             }
                             // create temp instance
                             $getid3_temp = new GetId3Core();
                             // analyze
                             $getid3_ogg = new 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 $key => $value) {
                                         $track_info[$key] = $value;
                                     }
                                 }
                             }
                             // copy errors and warnings
                             if (!empty($getid3_temp->info['error'])) {
                                 foreach ($getid3_temp->info['error'] as $newerror) {
                                     $this->getid3->warning('getid3_ogg() says: [' . $newerror . ']');
                                 }
                             }
                             if (!empty($getid3_temp->info['warning'])) {
                                 foreach ($getid3_temp->info['warning'] as $newerror) {
                                     $this->getid3->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':
                             if (!class_exists('GetId3\\Module\\AudioVideo\\Riff')) {
                                 $this->getid3->warning('Unable to parse audio data [' . basename(__FILE__) . ':' . __LINE__ . '] because cannot include "' . str_replace('_', DIRECTORY_SEPARATOR, 'GetId3\\Module\\AudioVideo\\Riff') . '.php"');
                                 break;
                             }
                             $parsed = Riff::RIFFparseWAVEFORMATex($trackarray['CodecPrivate']);
                             foreach ($parsed as $key => $value) {
                                 if ($key != 'raw') {
                                     $track_info[$key] = $value;
                                 }
                             }
                             $info['matroska']['track_codec_parsed'][$trackarray['TrackNumber']] = $parsed;
                             break;
                         default:
                             $this->getid3->warning('Unhandled audio type "' . (isset($trackarray['CodecID']) ? $trackarray['CodecID'] : '') . '"');
                     }
                     $info['audio']['streams'][] = $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']);
         }
     }
     // 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']);
     }
     return true;
 }
Пример #6
0
 /**
  * @return bool
  */
 public function setRealFileSize()
 {
     if (PHP_INT_MAX > 2147483647) {
         $this->filesize = filesize($this->filename);
         return true;
     }
     // 32-bit PHP will not return correct values for filesize() if file is >=2GB
     // but GetId3->analyze() has workarounds to get actual filesize
     $getID3 = new GetId3Core();
     $getID3->option_tag_id3v1 = false;
     $getID3->option_tag_id3v2 = false;
     $getID3->option_tag_apetag = false;
     $getID3->option_tags_html = false;
     $getID3->option_extra_info = false;
     $ThisFileInfo = $getID3->analyze($this->filename);
     $this->filesize = $ThisFileInfo['filesize'];
     return true;
 }
Пример #7
0
 /**
  * @return bool
  */
 public function analyze()
 {
     $info =& $this->getid3->info;
     $info['fileformat'] = 'quicktime';
     $info['quicktime']['hinting'] = false;
     $info['quicktime']['controller'] = 'standard';
     // may be overridden if 'ctyp' atom is present
     fseek($this->getid3->fp, $info['avdataoffset'], SEEK_SET);
     $offset = 0;
     $atomcounter = 0;
     while ($offset < $info['avdataend']) {
         if (!Helper::intValueSupported($offset)) {
             $info['error'][] = 'Unable to parse atom at offset ' . $offset . ' because beyond ' . round(PHP_INT_MAX / 1073741824) . 'GB limit of PHP filesystem functions';
             break;
         }
         fseek($this->getid3->fp, $offset, SEEK_SET);
         $AtomHeader = fread($this->getid3->fp, 8);
         $atomsize = Helper::BigEndian2Int(substr($AtomHeader, 0, 4));
         $atomname = substr($AtomHeader, 4, 4);
         // 64-bit MOV patch by jlegateØktnc*com
         if ($atomsize == 1) {
             $atomsize = Helper::BigEndian2Int(fread($this->getid3->fp, 8));
         }
         $info['quicktime'][$atomname]['name'] = $atomname;
         $info['quicktime'][$atomname]['size'] = $atomsize;
         $info['quicktime'][$atomname]['offset'] = $offset;
         if ($offset + $atomsize > $info['avdataend']) {
             $info['error'][] = 'Atom at offset ' . $offset . ' claims to go beyond end-of-file (length: ' . $atomsize . ' bytes)';
             return false;
         }
         if ($atomsize == 0) {
             // Furthermore, for historical reasons the list of atoms is optionally
             // terminated by a 32-bit integer set to 0. If you are writing a program
             // to read user data atoms, you should allow for the terminating 0.
             break;
         }
         switch ($atomname) {
             case 'mdat':
                 // Media DATa atom
                 // 'mdat' contains the actual data for the audio/video
                 if ($atomsize > 8 && (!isset($info['avdataend_tmp']) || $info['quicktime'][$atomname]['size'] > $info['avdataend_tmp'] - $info['avdataoffset'])) {
                     $info['avdataoffset'] = $info['quicktime'][$atomname]['offset'] + 8;
                     $OldAVDataEnd = $info['avdataend'];
                     $info['avdataend'] = $info['quicktime'][$atomname]['offset'] + $info['quicktime'][$atomname]['size'];
                     $getid3_temp = new GetId3Core();
                     $getid3_temp->openfile($this->getid3->filename);
                     $getid3_temp->info['avdataoffset'] = $info['avdataoffset'];
                     $getid3_temp->info['avdataend'] = $info['avdataend'];
                     $getid3_mp3 = new Module\Audio\Mp3($getid3_temp);
                     if ($getid3_mp3->MPEGaudioHeaderValid($getid3_mp3->MPEGaudioHeaderDecode(fread($this->getid3->fp, 4)))) {
                         $getid3_mp3->getOnlyMPEGaudioInfo($getid3_temp->info['avdataoffset'], false);
                         if (!empty($getid3_temp->info['warning'])) {
                             foreach ($getid3_temp->info['warning'] as $value) {
                                 $info['warning'][] = $value;
                             }
                         }
                         if (!empty($getid3_temp->info['mpeg'])) {
                             $info['mpeg'] = $getid3_temp->info['mpeg'];
                             if (isset($info['mpeg']['audio'])) {
                                 $info['audio']['dataformat'] = 'mp3';
                                 $info['audio']['codec'] = !empty($info['mpeg']['audio']['encoder']) ? $info['mpeg']['audio']['encoder'] : (!empty($info['mpeg']['audio']['codec']) ? $info['mpeg']['audio']['codec'] : (!empty($info['mpeg']['audio']['LAME']) ? 'LAME' : 'mp3'));
                                 $info['audio']['sample_rate'] = $info['mpeg']['audio']['sample_rate'];
                                 $info['audio']['channels'] = $info['mpeg']['audio']['channels'];
                                 $info['audio']['bitrate'] = $info['mpeg']['audio']['bitrate'];
                                 $info['audio']['bitrate_mode'] = strtolower($info['mpeg']['audio']['bitrate_mode']);
                                 $info['bitrate'] = $info['audio']['bitrate'];
                             }
                         }
                     }
                     unset($getid3_mp3, $getid3_temp);
                     $info['avdataend'] = $OldAVDataEnd;
                     unset($OldAVDataEnd);
                 }
                 break;
             case 'free':
                 // FREE space atom
             // FREE space atom
             case 'skip':
                 // SKIP atom
             // SKIP atom
             case 'wide':
                 // 64-bit expansion placeholder atom
                 // 'free', 'skip' and 'wide' are just padding, contains no useful data at all
                 break;
             default:
                 $atomHierarchy = array();
                 $info['quicktime'][$atomname] = $this->QuicktimeParseAtom($atomname, $atomsize, fread($this->getid3->fp, $atomsize), $offset, $atomHierarchy, $this->ParseAllPossibleAtoms);
                 break;
         }
         $offset += $atomsize;
         ++$atomcounter;
     }
     if (!empty($info['avdataend_tmp'])) {
         // this value is assigned to a temp value and then erased because
         // otherwise any atoms beyond the 'mdat' atom would not get parsed
         $info['avdataend'] = $info['avdataend_tmp'];
         unset($info['avdataend_tmp']);
     }
     if (!isset($info['bitrate']) && isset($info['playtime_seconds'])) {
         $info['bitrate'] = ($info['avdataend'] - $info['avdataoffset']) * 8 / $info['playtime_seconds'];
     }
     if (isset($info['bitrate']) && !isset($info['audio']['bitrate']) && !isset($info['quicktime']['video'])) {
         $info['audio']['bitrate'] = $info['bitrate'];
     }
     if (!empty($info['playtime_seconds']) && !isset($info['video']['frame_rate']) && !empty($info['quicktime']['stts_framecount'])) {
         foreach ($info['quicktime']['stts_framecount'] as $key => $samples_count) {
             $samples_per_second = $samples_count / $info['playtime_seconds'];
             if ($samples_per_second > 240) {
                 // has to be audio samples
             } else {
                 $info['video']['frame_rate'] = $samples_per_second;
                 break;
             }
         }
     }
     if ($info['audio']['dataformat'] == 'mp4' && empty($info['video']['resolution_x'])) {
         $info['fileformat'] = 'mp4';
         $info['mime_type'] = 'audio/mp4';
         unset($info['video']['dataformat']);
     }
     if (!$this->ReturnAtomData) {
         unset($info['quicktime']['moov']);
     }
     if (empty($info['audio']['dataformat']) && !empty($info['quicktime']['audio'])) {
         $info['audio']['dataformat'] = 'quicktime';
     }
     if (empty($info['video']['dataformat']) && !empty($info['quicktime']['video'])) {
         $info['video']['dataformat'] = 'quicktime';
     }
     return true;
 }
Пример #8
0
 /**
  * @return bool
  */
 public function DeleteMetaFLAC()
 {
     if (preg_match('#(1|ON)#i', ini_get('safe_mode'))) {
         $this->errors[] = 'PHP running in Safe Mode (backtick operator not available) - cannot call metaflac, tags not deleted';
         return false;
     }
     $oldignoreuserabort = ignore_user_abort(true);
     if (GetId3Core::environmentIsWindows()) {
         if (file_exists(GetId3Core::getHelperAppsDir() . 'metaflac.exe')) {
             // To at least see if there was a problem, compare file modification timestamps before and after writing
             clearstatcache();
             $timestampbeforewriting = filemtime($this->filename);
             $commandline = GetId3Core::getHelperAppsDir() . 'metaflac.exe --remove-all-tags "' . $this->filename . '" 2>&1';
             $metaflacError = `{$commandline}`;
             if (empty($metaflacError)) {
                 clearstatcache();
                 if ($timestampbeforewriting == filemtime($this->filename)) {
                     $metaflacError = 'File modification timestamp has not changed - it looks like the tags were not deleted';
                 }
             }
         } else {
             $metaflacError = 'metaflac.exe not found in ' . GetId3Core::getHelperAppsDir();
         }
     } else {
         // It's simpler on *nix
         $commandline = 'metaflac --remove-all-tags "' . $this->filename . '" 2>&1';
         $metaflacError = `{$commandline}`;
     }
     ignore_user_abort($oldignoreuserabort);
     if (!empty($metaflacError)) {
         $this->errors[] = 'System call to metaflac failed with this message returned: ' . "\n\n" . $metaflacError;
         return false;
     }
     return true;
 }
Пример #9
0
 /**
  * @return bool
  */
 public function analyze()
 {
     $info =& $this->getid3->info;
     // http://www.volweb.cz/str/tags.htm
     if (!Helper::intValueSupported($info['filesize'])) {
         $info['warning'][] = 'Unable to check for Lyrics3 because file is larger than ' . round(PHP_INT_MAX / 1073741824) . 'GB';
         return false;
     }
     fseek($this->getid3->fp, 0 - 128 - 9 - 6, SEEK_END);
     // end - ID3v1 - "LYRICSEND" - [Lyrics3size]
     $lyrics3_id3v1 = fread($this->getid3->fp, 128 + 9 + 6);
     $lyrics3lsz = substr($lyrics3_id3v1, 0, 6);
     // Lyrics3size
     $lyrics3end = substr($lyrics3_id3v1, 6, 9);
     // LYRICSEND or LYRICS200
     $id3v1tag = substr($lyrics3_id3v1, 15, 128);
     // ID3v1
     if ($lyrics3end == 'LYRICSEND') {
         // Lyrics3v1, ID3v1, no APE
         $lyrics3size = 5100;
         $lyrics3offset = $info['filesize'] - 128 - $lyrics3size;
         $lyrics3version = 1;
     } elseif ($lyrics3end == 'LYRICS200') {
         // Lyrics3v2, ID3v1, no APE
         // LSZ = lyrics + 'LYRICSBEGIN'; add 6-byte size field; add 'LYRICS200'
         $lyrics3size = $lyrics3lsz + 6 + strlen('LYRICS200');
         $lyrics3offset = $info['filesize'] - 128 - $lyrics3size;
         $lyrics3version = 2;
     } elseif (substr(strrev($lyrics3_id3v1), 0, 9) == strrev('LYRICSEND')) {
         // Lyrics3v1, no ID3v1, no APE
         $lyrics3size = 5100;
         $lyrics3offset = $info['filesize'] - $lyrics3size;
         $lyrics3version = 1;
         $lyrics3offset = $info['filesize'] - $lyrics3size;
     } elseif (substr(strrev($lyrics3_id3v1), 0, 9) == strrev('LYRICS200')) {
         // Lyrics3v2, no ID3v1, no APE
         $lyrics3size = strrev(substr(strrev($lyrics3_id3v1), 9, 6)) + 6 + strlen('LYRICS200');
         // LSZ = lyrics + 'LYRICSBEGIN'; add 6-byte size field; add 'LYRICS200'
         $lyrics3offset = $info['filesize'] - $lyrics3size;
         $lyrics3version = 2;
     } else {
         if (isset($info['ape']['tag_offset_start']) && $info['ape']['tag_offset_start'] > 15) {
             fseek($this->getid3->fp, $info['ape']['tag_offset_start'] - 15, SEEK_SET);
             $lyrics3lsz = fread($this->getid3->fp, 6);
             $lyrics3end = fread($this->getid3->fp, 9);
             if ($lyrics3end == 'LYRICSEND') {
                 // Lyrics3v1, APE, maybe ID3v1
                 $lyrics3size = 5100;
                 $lyrics3offset = $info['ape']['tag_offset_start'] - $lyrics3size;
                 $info['avdataend'] = $lyrics3offset;
                 $lyrics3version = 1;
                 $info['warning'][] = 'APE tag located after Lyrics3, will probably break Lyrics3 compatability';
             } elseif ($lyrics3end == 'LYRICS200') {
                 // Lyrics3v2, APE, maybe ID3v1
                 $lyrics3size = $lyrics3lsz + 6 + strlen('LYRICS200');
                 // LSZ = lyrics + 'LYRICSBEGIN'; add 6-byte size field; add 'LYRICS200'
                 $lyrics3offset = $info['ape']['tag_offset_start'] - $lyrics3size;
                 $lyrics3version = 2;
                 $info['warning'][] = 'APE tag located after Lyrics3, will probably break Lyrics3 compatability';
             }
         }
     }
     if (isset($lyrics3offset)) {
         $info['avdataend'] = $lyrics3offset;
         $this->getLyrics3Data($lyrics3offset, $lyrics3version, $lyrics3size);
         if (!isset($info['ape'])) {
             $GETID3_ERRORARRAY =& $info['warning'];
             if (class_exists('Helpers\\GetId3\\Module\\Tag\\Apetag')) {
                 $getid3_temp = new GetId3Core();
                 $getid3_temp->openfile($this->getid3->filename);
                 $getid3_apetag = new Apetag($getid3_temp);
                 $getid3_apetag->overrideendoffset = $info['lyrics3']['tag_offset_start'];
                 $getid3_apetag->analyze();
                 if (!empty($getid3_temp->info['ape'])) {
                     $info['ape'] = $getid3_temp->info['ape'];
                 }
                 if (!empty($getid3_temp->info['replay_gain'])) {
                     $info['replay_gain'] = $getid3_temp->info['replay_gain'];
                 }
                 unset($getid3_temp, $getid3_apetag);
             }
         }
     }
     return true;
 }
Пример #10
0
 /**
  * @return bool
  */
 public function WriteTags()
 {
     if (empty($this->filename)) {
         $this->errors[] = 'filename is undefined in GetId3_writetags';
         return false;
     } elseif (!file_exists($this->filename)) {
         $this->errors[] = 'filename set to non-existant file "' . $this->filename . '" in GetId3_writetags';
         return false;
     }
     if (!is_array($this->tagformats)) {
         $this->errors[] = 'tagformats must be an array in GetId3_writetags';
         return false;
     }
     $TagFormatsToRemove = array();
     if (filesize($this->filename) == 0) {
         // empty file special case - allow any tag format, don't check existing format
         // could be useful if you want to generate tag data for a non-existant file
         $this->ThisFileInfo = array('fileformat' => '');
         $AllowedTagFormats = array('id3v1', 'id3v2.2', 'id3v2.3', 'id3v2.4', 'ape', 'lyrics3');
     } else {
         $getID3 = new GetId3Core();
         $getID3->setEncoding($this->tag_encoding);
         $this->ThisFileInfo = $getID3->analyze($this->filename);
         // check for what file types are allowed on this fileformat
         switch (isset($this->ThisFileInfo['fileformat']) ? $this->ThisFileInfo['fileformat'] : '') {
             case 'mp3':
             case 'mp2':
             case 'mp1':
             case 'riff':
                 // maybe not officially, but people do it anyway
                 $AllowedTagFormats = array('id3v1', 'id3v2.2', 'id3v2.3', 'id3v2.4', 'ape', 'lyrics3');
                 break;
             case 'mpc':
                 $AllowedTagFormats = array('ape');
                 break;
             case 'flac':
                 $AllowedTagFormats = array('metaflac');
                 break;
             case 'real':
                 $AllowedTagFormats = array('real');
                 break;
             case 'ogg':
                 switch (isset($this->ThisFileInfo['audio']['dataformat']) ? $this->ThisFileInfo['audio']['dataformat'] : '') {
                     case 'flac':
                         //$AllowedTagFormats = array('metaflac');
                         $this->errors[] = 'metaflac is not (yet) compatible with OggFLAC files';
                         return false;
                         break;
                     case 'vorbis':
                         $AllowedTagFormats = array('vorbiscomment');
                         break;
                     default:
                         $this->errors[] = 'metaflac is not (yet) compatible with Ogg files other than OggVorbis';
                         return false;
                         break;
                 }
                 break;
             default:
                 $AllowedTagFormats = array();
                 break;
         }
         foreach ($this->tagformats as $requested_tag_format) {
             if (!in_array($requested_tag_format, $AllowedTagFormats)) {
                 $errormessage = 'Tag format "' . $requested_tag_format . '" is not allowed on "' . (isset($this->ThisFileInfo['fileformat']) ? $this->ThisFileInfo['fileformat'] : '');
                 $errormessage .= isset($this->ThisFileInfo['audio']['dataformat']) ? '.' . $this->ThisFileInfo['audio']['dataformat'] : '';
                 $errormessage .= '" files';
                 $this->errors[] = $errormessage;
                 return false;
             }
         }
         // List of other tag formats, removed if requested
         if ($this->remove_other_tags) {
             foreach ($AllowedTagFormats as $AllowedTagFormat) {
                 switch ($AllowedTagFormat) {
                     case 'id3v2.2':
                     case 'id3v2.3':
                     case 'id3v2.4':
                         if (!in_array('id3v2', $TagFormatsToRemove) && !in_array('id3v2.2', $this->tagformats) && !in_array('id3v2.3', $this->tagformats) && !in_array('id3v2.4', $this->tagformats)) {
                             $TagFormatsToRemove[] = 'id3v2';
                         }
                         break;
                     default:
                         if (!in_array($AllowedTagFormat, $this->tagformats)) {
                             $TagFormatsToRemove[] = $AllowedTagFormat;
                         }
                         break;
                 }
             }
         }
     }
     $WritingFilesToInclude = array_merge($this->tagformats, $TagFormatsToRemove);
     // Check for required include files and include them
     foreach ($WritingFilesToInclude as $tagformat) {
         switch ($tagformat) {
             case 'ape':
                 $GETID3_ERRORARRAY =& $this->errors;
                 if (!class_exists('Helpers\\GetId3\\Write\\Apetag')) {
                     return false;
                 }
                 break;
             case 'id3v1':
             case 'lyrics3':
             case 'vorbiscomment':
             case 'metaflac':
             case 'real':
                 $GETID3_ERRORARRAY =& $this->errors;
                 if (!class_exists('Helpers\\GetId3\\Write\\' . ucfirst($tagformat))) {
                     return false;
                 }
                 break;
             case 'id3v2.2':
             case 'id3v2.3':
             case 'id3v2.4':
             case 'id3v2':
                 $GETID3_ERRORARRAY =& $this->errors;
                 if (!class_exists('Helpers\\GetId3\\Write\\Id3v2')) {
                     return false;
                 }
                 break;
             default:
                 $this->errors[] = 'unknown tag format "' . $tagformat . '" in $tagformats in WriteTags()';
                 return false;
                 break;
         }
     }
     // Validation of supplied data
     if (!is_array($this->tag_data)) {
         $this->errors[] = '$this->tag_data is not an array in WriteTags()';
         return false;
     }
     // convert supplied data array keys to upper case, if they're not already
     foreach ($this->tag_data as $tag_key => $tag_array) {
         if (strtoupper($tag_key) !== $tag_key) {
             $this->tag_data[strtoupper($tag_key)] = $this->tag_data[$tag_key];
             unset($this->tag_data[$tag_key]);
         }
     }
     // convert source data array keys to upper case, if they're not already
     if (!empty($this->ThisFileInfo['tags'])) {
         foreach ($this->ThisFileInfo['tags'] as $tag_format => $tag_data_array) {
             foreach ($tag_data_array as $tag_key => $tag_array) {
                 if (strtoupper($tag_key) !== $tag_key) {
                     $this->ThisFileInfo['tags'][$tag_format][strtoupper($tag_key)] = $this->ThisFileInfo['tags'][$tag_format][$tag_key];
                     unset($this->ThisFileInfo['tags'][$tag_format][$tag_key]);
                 }
             }
         }
     }
     // Convert "TRACK" to "TRACKNUMBER" (if needed) for compatability with all formats
     if (isset($this->tag_data['TRACK']) && !isset($this->tag_data['TRACKNUMBER'])) {
         $this->tag_data['TRACKNUMBER'] = $this->tag_data['TRACK'];
         unset($this->tag_data['TRACK']);
     }
     // Remove all other tag formats, if requested
     if ($this->remove_other_tags) {
         $this->DeleteTags($TagFormatsToRemove);
     }
     // Write data for each tag format
     foreach ($this->tagformats as $tagformat) {
         $success = false;
         // overridden if tag writing is successful
         switch ($tagformat) {
             case 'ape':
                 $ape_writer = new Apetag();
                 if (($ape_writer->tag_data = $this->FormatDataForAPE()) !== false) {
                     $ape_writer->filename = $this->filename;
                     if (($success = $ape_writer->WriteAPEtag()) === false) {
                         $this->errors[] = 'WriteAPEtag() failed with message(s):<pre><ul><li>' . str_replace("\n", '</li><li>', htmlentities(trim(implode("\n", $ape_writer->errors)))) . '</li></ul></pre>';
                     }
                 } else {
                     $this->errors[] = 'FormatDataForAPE() failed';
                 }
                 break;
             case 'id3v1':
                 $id3v1_writer = new Id3v1();
                 if (($id3v1_writer->tag_data = $this->FormatDataForID3v1()) !== false) {
                     $id3v1_writer->filename = $this->filename;
                     if (($success = $id3v1_writer->WriteID3v1()) === false) {
                         $this->errors[] = 'WriteID3v1() failed with message(s):<pre><ul><li>' . str_replace("\n", '</li><li>', htmlentities(trim(implode("\n", $id3v1_writer->errors)))) . '</li></ul></pre>';
                     }
                 } else {
                     $this->errors[] = 'FormatDataForID3v1() failed';
                 }
                 break;
             case 'id3v2.2':
             case 'id3v2.3':
             case 'id3v2.4':
                 $id3v2_writer = new Id3v2();
                 $id3v2_writer->majorversion = intval(substr($tagformat, -1));
                 $id3v2_writer->paddedlength = $this->id3v2_paddedlength;
                 if (($id3v2_writer->tag_data = $this->FormatDataForID3v2($id3v2_writer->majorversion)) !== false) {
                     $id3v2_writer->filename = $this->filename;
                     if (($success = $id3v2_writer->WriteID3v2()) === false) {
                         $this->errors[] = 'WriteID3v2() failed with message(s):<pre><ul><li>' . str_replace("\n", '</li><li>', htmlentities(trim(implode("\n", $id3v2_writer->errors)))) . '</li></ul></pre>';
                     }
                 } else {
                     $this->errors[] = 'FormatDataForID3v2() failed';
                 }
                 break;
             case 'vorbiscomment':
                 $vorbiscomment_writer = new Vorbiscomment();
                 if (($vorbiscomment_writer->tag_data = $this->FormatDataForVorbisComment()) !== false) {
                     $vorbiscomment_writer->filename = $this->filename;
                     if (($success = $vorbiscomment_writer->WriteVorbisComment()) === false) {
                         $this->errors[] = 'WriteVorbisComment() failed with message(s):<pre><ul><li>' . str_replace("\n", '</li><li>', htmlentities(trim(implode("\n", $vorbiscomment_writer->errors)))) . '</li></ul></pre>';
                     }
                 } else {
                     $this->errors[] = 'FormatDataForVorbisComment() failed';
                 }
                 break;
             case 'metaflac':
                 $metaflac_writer = new Metaflac();
                 if (($metaflac_writer->tag_data = $this->FormatDataForMetaFLAC()) !== false) {
                     $metaflac_writer->filename = $this->filename;
                     if (($success = $metaflac_writer->WriteMetaFLAC()) === false) {
                         $this->errors[] = 'WriteMetaFLAC() failed with message(s):<pre><ul><li>' . str_replace("\n", '</li><li>', htmlentities(trim(implode("\n", $metaflac_writer->errors)))) . '</li></ul></pre>';
                     }
                 } else {
                     $this->errors[] = 'FormatDataForMetaFLAC() failed';
                 }
                 break;
             case 'real':
                 $real_writer = new Real();
                 if (($real_writer->tag_data = $this->FormatDataForReal()) !== false) {
                     $real_writer->filename = $this->filename;
                     if (($success = $real_writer->WriteReal()) === false) {
                         $this->errors[] = 'WriteReal() failed with message(s):<pre><ul><li>' . str_replace("\n", '</li><li>', htmlentities(trim(implode("\n", $real_writer->errors)))) . '</li></ul></pre>';
                     }
                 } else {
                     $this->errors[] = 'FormatDataForReal() failed';
                 }
                 break;
             default:
                 $this->errors[] = 'Invalid tag format to write: "' . $tagformat . '"';
                 return false;
                 break;
         }
         if (!$success) {
             return false;
         }
     }
     return true;
 }
Пример #11
0
 /**
  * @return bool
  */
 public function WriteVorbisComment()
 {
     if (preg_match('#(1|ON)#i', ini_get('safe_mode'))) {
         $this->errors[] = 'PHP running in Safe Mode (backtick operator not available) - cannot call vorbiscomment, tags not written';
         return false;
     }
     // Create file with new comments
     $tempcommentsfilename = tempnam(GetId3Core::getTempDir(), 'getID3');
     if (is_writable($tempcommentsfilename) && is_file($tempcommentsfilename) && ($fpcomments = fopen($tempcommentsfilename, 'wb'))) {
         foreach ($this->tag_data as $key => $value) {
             foreach ($value as $commentdata) {
                 fwrite($fpcomments, $this->CleanVorbisCommentName($key) . '=' . $commentdata . "\n");
             }
         }
         fclose($fpcomments);
     } else {
         $this->errors[] = 'failed to open temporary tags file "' . $tempcommentsfilename . '", tags not written';
         return false;
     }
     $oldignoreuserabort = ignore_user_abort(true);
     if (GetId3Core::environmentIsWindows()) {
         if (file_exists(GetId3Core::getHelperAppsDir() . 'vorbiscomment.exe')) {
             //$commandline = '"'.GetId3Core::getHelperAppsDir().'vorbiscomment.exe" -w --raw -c "'.$tempcommentsfilename.'" "'.str_replace('/', '\\', $this->filename).'"';
             //  vorbiscomment works fine if you copy-paste the above commandline into a command prompt,
             //  but refuses to work with `backtick` if there are "doublequotes" present around BOTH
             //  the metaflac pathname and the target filename. For whatever reason...??
             //  The solution is simply ensure that the metaflac pathname has no spaces,
             //  and therefore does not need to be quoted
             // On top of that, if error messages are not always captured properly under Windows
             // To at least see if there was a problem, compare file modification timestamps before and after writing
             clearstatcache();
             $timestampbeforewriting = filemtime($this->filename);
             $commandline = GetId3Core::getHelperAppsDir() . 'vorbiscomment.exe -w --raw -c "' . $tempcommentsfilename . '" "' . $this->filename . '" 2>&1';
             $VorbiscommentError = `{$commandline}`;
             if (empty($VorbiscommentError)) {
                 clearstatcache();
                 if ($timestampbeforewriting == filemtime($this->filename)) {
                     $VorbiscommentError = 'File modification timestamp has not changed - it looks like the tags were not written';
                 }
             }
         } else {
             $VorbiscommentError = 'vorbiscomment.exe not found in ' . GetId3Core::getHelperAppsDir();
         }
     } else {
         $commandline = 'vorbiscomment -w --raw -c "' . $tempcommentsfilename . '" "' . $this->filename . '" 2>&1';
         $VorbiscommentError = `{$commandline}`;
     }
     // Remove temporary comments file
     unlink($tempcommentsfilename);
     ignore_user_abort($oldignoreuserabort);
     if (!empty($VorbiscommentError)) {
         $this->errors[] = 'system call to vorbiscomment failed with message: ' . "\n\n" . $VorbiscommentError;
         return false;
     }
     return true;
 }
Пример #12
0
 /**
  * self::md5_data() - returns md5sum for a file from startuing position to absolute end position
  *
  * @staticvar string $tempdir
  *
  * @param  type      $file
  * @param  type      $offset
  * @param  type      $end
  * @param  type      $algorithm
  *
  * @return bool
  *
  * @throws Exception
  *
  * @author Allan Hansen <ahØartemis*dk>
  */
 public static function hash_data($file, $offset, $end, $algorithm)
 {
     static $tempdir = '';
     if (!self::intValueSupported($end)) {
         return false;
     }
     switch ($algorithm) {
         case 'md5':
             $hash_function = 'md5_file';
             $unix_call = 'md5sum';
             $windows_call = 'md5sum.exe';
             $hash_length = 32;
             break;
         case 'sha1':
             $hash_function = 'sha1_file';
             $unix_call = 'sha1sum';
             $windows_call = 'sha1sum.exe';
             $hash_length = 40;
             break;
         default:
             throw new DefaultException('Invalid algorithm (' . $algorithm . ') in self::hash_data()');
             break;
     }
     $size = $end - $offset;
     while (true) {
         if (GetId3Core::environmentIsWindows()) {
             // It seems that sha1sum.exe for Windows only works on physical files, does not accept piped data
             // Fall back to create-temp-file method:
             if ($algorithm == 'sha1') {
                 break;
             }
             $RequiredFiles = array('cygwin1.dll', 'head.exe', 'tail.exe', $windows_call);
             foreach ($RequiredFiles as $required_file) {
                 if (!is_readable(GetId3Core::getHelperAppsDir() . $required_file)) {
                     // helper apps not available - fall back to old method
                     break 2;
                 }
             }
             $commandline = GetId3Core::getHelperAppsDir() . 'head.exe -c ' . $end . ' ' . escapeshellarg(str_replace('/', DIRECTORY_SEPARATOR, $file)) . ' | ';
             $commandline .= GetId3Core::getHelperAppsDir() . 'tail.exe -c ' . $size . ' | ';
             $commandline .= GetId3Core::getHelperAppsDir() . $windows_call;
         } else {
             $commandline = 'head -c' . $end . ' ' . escapeshellarg($file) . ' | ';
             $commandline .= 'tail -c' . $size . ' | ';
             $commandline .= $unix_call;
         }
         if (preg_match('#(1|ON)#i', ini_get('safe_mode'))) {
             //throw new DefaultException('PHP running in Safe Mode - backtick operator not available, using slower non-system-call '.$algorithm.' algorithm');
             break;
         }
         return substr(`{$commandline}`, 0, $hash_length);
     }
     if (empty($tempdir)) {
         // yes this is ugly, feel free to suggest a better way
         $getid3_temp = new GetId3Core();
         $tempdir = $getid3_temp->tempdir;
         unset($getid3_temp);
     }
     // try to create a temporary file in the system temp directory - invalid dirname should force to system temp dir
     if (($data_filename = tempnam($tempdir, 'gI3')) === false) {
         // can't find anywhere to create a temp file, just fail
         return false;
     }
     // Init
     $result = false;
     // copy parts of file
     try {
         self::CopyFileParts($file, $data_filename, $offset, $end - $offset);
         $result = $hash_function($data_filename);
     } catch (DefaultException $e) {
         throw new DefaultException('self::CopyFileParts() failed in getid_lib::hash_data(): ' . $e->getMessage());
     }
     unlink($data_filename);
     return $result;
 }
Пример #13
0
 /**
  * @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';
     fseek($this->getid3->fp, $info['avdataoffset'], SEEK_SET);
     $HeaderObjectData = fread($this->getid3->fp, 30);
     $thisfile_asf_headerobject['objectid'] = substr($HeaderObjectData, 0, 16);
     $thisfile_asf_headerobject['objectid_guid'] = self::BytestringToGUID($thisfile_asf_headerobject['objectid']);
     if ($thisfile_asf_headerobject['objectid'] != self::$GETID3_ASF_Header_Object) {
         $info['warning'][] = 'ASF header GUID {' . self::BytestringToGUID($thisfile_asf_headerobject['objectid']) . '} does not match expected "GETID3_ASF_Header_Object" GUID {' . self::BytestringToGUID(self::$GETID3_ASF_Header_Object) . '}';
         unset($info['fileformat']);
         unset($info['asf']);
         return false;
     }
     $thisfile_asf_headerobject['objectsize'] = Helper::LittleEndian2Int(substr($HeaderObjectData, 16, 8));
     $thisfile_asf_headerobject['headerobjects'] = Helper::LittleEndian2Int(substr($HeaderObjectData, 24, 4));
     $thisfile_asf_headerobject['reserved1'] = Helper::LittleEndian2Int(substr($HeaderObjectData, 28, 1));
     $thisfile_asf_headerobject['reserved2'] = Helper::LittleEndian2Int(substr($HeaderObjectData, 29, 1));
     $NextObjectOffset = ftell($this->getid3->fp);
     $ASFHeaderData = fread($this->getid3->fp, $thisfile_asf_headerobject['objectsize'] - 30);
     $offset = 0;
     for ($HeaderObjectsCounter = 0; $HeaderObjectsCounter < $thisfile_asf_headerobject['headerobjects']; ++$HeaderObjectsCounter) {
         $NextObjectGUID = substr($ASFHeaderData, $offset, 16);
         $offset += 16;
         $NextObjectGUIDtext = self::BytestringToGUID($NextObjectGUID);
         $NextObjectSize = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 8));
         $offset += 8;
         switch ($NextObjectGUID) {
             case self::$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'] = self::BytestringToGUID($thisfile_asf_filepropertiesobject['fileid']);
                 $thisfile_asf_filepropertiesobject['filesize'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 8));
                 $offset += 8;
                 $thisfile_asf_filepropertiesobject['creation_date'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 8));
                 $thisfile_asf_filepropertiesobject['creation_date_unix'] = self::FILETIMEtoUNIXtime($thisfile_asf_filepropertiesobject['creation_date']);
                 $offset += 8;
                 $thisfile_asf_filepropertiesobject['data_packets'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 8));
                 $offset += 8;
                 $thisfile_asf_filepropertiesobject['play_duration'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 8));
                 $offset += 8;
                 $thisfile_asf_filepropertiesobject['send_duration'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 8));
                 $offset += 8;
                 $thisfile_asf_filepropertiesobject['preroll'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 8));
                 $offset += 8;
                 $thisfile_asf_filepropertiesobject['flags_raw'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 4));
                 $offset += 4;
                 $thisfile_asf_filepropertiesobject['flags']['broadcast'] = (bool) ($thisfile_asf_filepropertiesobject['flags_raw'] & 0x1);
                 $thisfile_asf_filepropertiesobject['flags']['seekable'] = (bool) ($thisfile_asf_filepropertiesobject['flags_raw'] & 0x2);
                 $thisfile_asf_filepropertiesobject['min_packet_size'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 4));
                 $offset += 4;
                 $thisfile_asf_filepropertiesobject['max_packet_size'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 4));
                 $offset += 4;
                 $thisfile_asf_filepropertiesobject['max_bitrate'] = Helper::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'] = (isset($thisfile_asf_filepropertiesobject['filesize']) ? $thisfile_asf_filepropertiesobject['filesize'] : $info['filesize']) * 8 / $info['playtime_seconds'];
                 }
                 break;
             case self::$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 self::$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 = array();
                 $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'] = self::BytestringToGUID($StreamPropertiesObjectData['stream_type']);
                 $StreamPropertiesObjectData['error_correct_type'] = substr($ASFHeaderData, $offset, 16);
                 $offset += 16;
                 $StreamPropertiesObjectData['error_correct_guid'] = self::BytestringToGUID($StreamPropertiesObjectData['error_correct_type']);
                 $StreamPropertiesObjectData['time_offset'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 8));
                 $offset += 8;
                 $StreamPropertiesObjectData['type_data_length'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 4));
                 $offset += 4;
                 $StreamPropertiesObjectData['error_data_length'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 4));
                 $offset += 4;
                 $StreamPropertiesObjectData['flags_raw'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
                 $offset += 2;
                 $StreamPropertiesObjectStreamNumber = $StreamPropertiesObjectData['flags_raw'] & 0x7f;
                 $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 self::$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 = Riff::RIFFparseWAVEFORMATex(substr($StreamPropertiesObjectData['type_specific_data'], 0, 16));
                         unset($audiodata['raw']);
                         $thisfile_audio = Helper::array_merge_noclobber($audiodata, $thisfile_audio);
                         break;
                     case self::$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 self::$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 self::$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'] = self::BytestringToGUID($thisfile_asf_headerextensionobject['reserved_1']);
                 if ($thisfile_asf_headerextensionobject['reserved_1'] != self::$GETID3_ASF_Reserved_1) {
                     $info['warning'][] = 'header_extension_object.reserved_1 GUID (' . self::BytestringToGUID($thisfile_asf_headerextensionobject['reserved_1']) . ') does not match expected "GETID3_ASF_Reserved_1" GUID (' . self::BytestringToGUID(self::$GETID3_ASF_Reserved_1) . ')';
                     //return false;
                     break;
                 }
                 $thisfile_asf_headerextensionobject['reserved_2'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
                 $offset += 2;
                 if ($thisfile_asf_headerextensionobject['reserved_2'] != 6) {
                     $info['warning'][] = 'header_extension_object.reserved_2 (' . Helper::PrintHexBytes($thisfile_asf_headerextensionobject['reserved_2']) . ') does not match expected value of "6"';
                     //return false;
                     break;
                 }
                 $thisfile_asf_headerextensionobject['extension_data_size'] = Helper::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->ASF_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 self::$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();
                 $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'] = self::BytestringToGUID($thisfile_asf_codeclistobject['reserved']);
                 if ($thisfile_asf_codeclistobject['reserved'] != self::GUIDtoBytestring('86D15241-311D-11D0-A3A4-00A0C90348F6')) {
                     $info['warning'][] = 'codec_list_object.reserved GUID {' . self::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'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 4));
                 $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'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
                     $offset += 2;
                     $thisfile_asf_codeclistobject_codecentries_current['type'] = $this->ASFCodecListObjectTypeLookup($thisfile_asf_codeclistobject_codecentries_current['type_raw']);
                     $CodecNameLength = Helper::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 = Helper::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 = Helper::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) {
                             $info['warning'][] = '[asf][codec_list_object][codec_entries][' . $CodecEntryCounter . '][description] expected to contain comma-seperated list of parameters: "' . $thisfile_asf_codeclistobject_codecentries_current['description'] . '"';
                         } else {
                             list($AudioCodecBitrate, $AudioCodecFrequency, $AudioCodecChannels) = explode(',', self::TrimConvert($thisfile_asf_codeclistobject_codecentries_current['description']));
                             $thisfile_audio['codec'] = self::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:
                                     $info['warning'][] = 'unknown frequency: "' . $AudioCodecFrequency . '" (' . self::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 self::$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'] = self::BytestringToGUID($thisfile_asf_scriptcommandobject['reserved']);
                 if ($thisfile_asf_scriptcommandobject['reserved'] != self::GUIDtoBytestring('4B1ACBE3-100B-11D0-A39B-00A0C90348F6')) {
                     $info['warning'][] = 'script_command_object.reserved GUID {' . self::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'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
                 $offset += 2;
                 $thisfile_asf_scriptcommandobject['command_types_count'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
                 $offset += 2;
                 for ($CommandTypesCounter = 0; $CommandTypesCounter < $thisfile_asf_scriptcommandobject['command_types_count']; ++$CommandTypesCounter) {
                     $CommandTypeNameLength = Helper::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'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 4));
                     $offset += 4;
                     $thisfile_asf_scriptcommandobject['commands'][$CommandsCounter]['type_index'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
                     $offset += 2;
                     $CommandTypeNameLength = Helper::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 self::$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'] = self::BytestringToGUID($thisfile_asf_markerobject['reserved']);
                 if ($thisfile_asf_markerobject['reserved'] != self::GUIDtoBytestring('4CFEDB20-75F6-11CF-9C0F-00A0C90349CB')) {
                     $info['warning'][] = 'marker_object.reserved GUID {' . self::BytestringToGUID($thisfile_asf_markerobject['reserved_1']) . '} does not match expected "GETID3_ASF_Reserved_1" GUID {4CFEDB20-75F6-11CF-9C0F-00A0C90349CB}';
                     break;
                 }
                 $thisfile_asf_markerobject['markers_count'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 4));
                 $offset += 4;
                 $thisfile_asf_markerobject['reserved_2'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
                 $offset += 2;
                 if ($thisfile_asf_markerobject['reserved_2'] != 0) {
                     $info['warning'][] = 'marker_object.reserved_2 (' . Helper::PrintHexBytes($thisfile_asf_markerobject['reserved_2']) . ') does not match expected value of "0"';
                     break;
                 }
                 $thisfile_asf_markerobject['name_length'] = Helper::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'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 8));
                     $offset += 8;
                     $thisfile_asf_markerobject['markers'][$MarkersCounter]['presentation_time'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 8));
                     $offset += 8;
                     $thisfile_asf_markerobject['markers'][$MarkersCounter]['entry_length'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
                     $offset += 2;
                     $thisfile_asf_markerobject['markers'][$MarkersCounter]['send_time'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 4));
                     $offset += 4;
                     $thisfile_asf_markerobject['markers'][$MarkersCounter]['flags'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 4));
                     $offset += 4;
                     $thisfile_asf_markerobject['markers'][$MarkersCounter]['marker_description_length'] = Helper::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 self::$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'] = self::BytestringToGUID($thisfile_asf_bitratemutualexclusionobject['reserved']);
                 $offset += 16;
                 if ($thisfile_asf_bitratemutualexclusionobject['reserved'] != self::$GETID3_ASF_Mutex_Bitrate && $thisfile_asf_bitratemutualexclusionobject['reserved'] != self::$GETID3_ASF_Mutex_Unknown) {
                     $info['warning'][] = 'bitrate_mutual_exclusion_object.reserved GUID {' . self::BytestringToGUID($thisfile_asf_bitratemutualexclusionobject['reserved']) . '} does not match expected "GETID3_ASF_Mutex_Bitrate" GUID {' . self::BytestringToGUID(self::$GETID3_ASF_Mutex_Bitrate) . '} or  "GETID3_ASF_Mutex_Unknown" GUID {' . self::BytestringToGUID(self::$GETID3_ASF_Mutex_Unknown) . '}';
                     //return false;
                     break;
                 }
                 $thisfile_asf_bitratemutualexclusionobject['stream_numbers_count'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
                 $offset += 2;
                 for ($StreamNumberCounter = 0; $StreamNumberCounter < $thisfile_asf_bitratemutualexclusionobject['stream_numbers_count']; ++$StreamNumberCounter) {
                     $thisfile_asf_bitratemutualexclusionobject['stream_numbers'][$StreamNumberCounter] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
                     $offset += 2;
                 }
                 break;
             case self::$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'] = self::BytestringToGUID($thisfile_asf_errorcorrectionobject['error_correction_type']);
                 $thisfile_asf_errorcorrectionobject['error_correction_data_length'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 4));
                 $offset += 4;
                 switch ($thisfile_asf_errorcorrectionobject['error_correction_type']) {
                     case self::$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 self::$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'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 1));
                         $offset += 1;
                         $thisfile_asf_errorcorrectionobject['virtual_packet_length'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
                         $offset += 2;
                         $thisfile_asf_errorcorrectionobject['virtual_chunk_length'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
                         $offset += 2;
                         $thisfile_asf_errorcorrectionobject['silence_data_length'] = Helper::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:
                         $info['warning'][] = 'error_correction_object.error_correction_type GUID {' . self::BytestringToGUID($thisfile_asf_errorcorrectionobject['reserved']) . '} does not match expected "GETID3_ASF_No_Error_Correction" GUID {' . self::BytestringToGUID(self::$GETID3_ASF_No_Error_Correction) . '} or  "GETID3_ASF_Audio_Spread" GUID {' . self::BytestringToGUID(self::$GETID3_ASF_Audio_Spread) . '}';
                         //return false;
                         break;
                 }
                 break;
             case self::$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'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
                 $offset += 2;
                 $thisfile_asf_contentdescriptionobject['author_length'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
                 $offset += 2;
                 $thisfile_asf_contentdescriptionobject['copyright_length'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
                 $offset += 2;
                 $thisfile_asf_contentdescriptionobject['description_length'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
                 $offset += 2;
                 $thisfile_asf_contentdescriptionobject['rating_length'] = Helper::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][] = self::TrimTerm($thisfile_asf_contentdescriptionobject[$keytocopyfrom]);
                     }
                 }
                 break;
             case self::$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'] = Helper::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'] = Helper::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'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
                     $offset += 2;
                     $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value_length'] = Helper::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 0x0:
                             // Unicode string
                             break;
                         case 0x1:
                             // BYTE array
                             // do nothing
                             break;
                         case 0x2:
                             // BOOL
                             $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value'] = (bool) Helper::LittleEndian2Int($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value']);
                             break;
                         case 0x3:
                             // DWORD
                         // DWORD
                         case 0x4:
                             // QWORD
                         // QWORD
                         case 0x5:
                             // WORD
                             $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value'] = Helper::LittleEndian2Int($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value']);
                             break;
                         default:
                             $info['warning'][] = 'extended_content_description.content_descriptors.' . $ExtendedContentDescriptorsCounter . '.value_type is invalid (' . $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value_type'] . ')';
                             //return false;
                             break;
                     }
                     switch (self::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(self::TrimTerm($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value']));
                             break;
                         case 'wm/albumtitle':
                         case 'album':
                             $thisfile_asf_comments['album'] = array(self::TrimTerm($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value']));
                             break;
                         case 'wm/genre':
                         case 'genre':
                             $thisfile_asf_comments['genre'] = array(self::TrimTerm($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value']));
                             break;
                         case 'wm/partofset':
                             $thisfile_asf_comments['partofset'] = array(self::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'] = array(self::TrimTerm($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value']));
                             foreach ($thisfile_asf_comments['track'] as $key => $value) {
                                 if (preg_match('/^[0-9\\x00]+$/', $value)) {
                                     $thisfile_asf_comments['track'][$key] = intval(str_replace("", '', $value));
                                 }
                             }
                             break;
                         case 'wm/track':
                             if (empty($thisfile_asf_comments['track'])) {
                                 $thisfile_asf_comments['track'] = array(1 + self::TrimConvert($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value']));
                             }
                             break;
                         case 'wm/year':
                         case 'year':
                         case 'date':
                             $thisfile_asf_comments['year'] = array(self::TrimTerm($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value']));
                             break;
                         case 'wm/lyrics':
                         case 'lyrics':
                             $thisfile_asf_comments['lyrics'] = array(self::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':
                             // id3v2 module might not be loaded
                             if (class_exists('getid3_id3v2')) {
                                 $tempfile = tempnam(GetId3Core::getTempDir(), 'getID3');
                                 $tempfilehandle = fopen($tempfile, 'wb');
                                 $tempThisfileInfo = array('encoding' => $info['encoding']);
                                 fwrite($tempfilehandle, $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value']);
                                 fclose($tempfilehandle);
                                 $getid3_temp = new GetId3Core();
                                 $getid3_temp->openfile($tempfile);
                                 $getid3_id3v2 = new Id3v2($getid3_temp);
                                 $getid3_id3v2->analyze();
                                 $info['id3v2'] = $getid3_temp->info['id3v2'];
                                 unset($getid3_temp, $getid3_id3v2);
                                 unlink($tempfile);
                             }
                             break;
                         case 'wm/encodingtime':
                             $thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['encoding_time_unix'] = self::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']    = $this->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(self::TrimConvert($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['name']), 0, 3) == 'WM/') {
                                         $thisfile_asf_comments[str_replace('wm/', '', strtolower(self::TrimConvert($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['name'])))] = array(self::TrimTerm($thisfile_asf_extendedcontentdescriptionobject_contentdescriptor_current['value']));
                                     }
                                     break;
                                 case 1:
                                     break;
                             }
                             break;
                     }
                 }
                 break;
             case self::$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'] = Helper::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'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 2));
                     $offset += 2;
                     $thisfile_asf_streambitratepropertiesobject['bitrate_records'][$BitrateRecordsCounter]['flags']['stream_number'] = $thisfile_asf_streambitratepropertiesobject['bitrate_records'][$BitrateRecordsCounter]['flags_raw'] & 0x7f;
                     $thisfile_asf_streambitratepropertiesobject['bitrate_records'][$BitrateRecordsCounter]['bitrate'] = Helper::LittleEndian2Int(substr($ASFHeaderData, $offset, 4));
                     $offset += 4;
                 }
                 break;
             case self::$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 self::$GETID3_ASF_Extended_Content_Encryption_Object:
             case self::$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 (self::GUIDname($NextObjectGUIDtext)) {
                     $info['warning'][] = 'unhandled GUID "' . self::GUIDname($NextObjectGUIDtext) . '" {' . $NextObjectGUIDtext . '} in ASF header at offset ' . ($offset - 16 - 8);
                 } else {
                     $info['warning'][] = 'unknown GUID {' . $NextObjectGUIDtext . '} in ASF header at offset ' . ($offset - 16 - 8);
                 }
                 $offset += $NextObjectSize - 16 - 8;
                 break;
         }
     }
     if (isset($thisfile_asf_streambitrateproperties['bitrate_records_count'])) {
         $ASFbitrateAudio = 0;
         $ASFbitrateVideo = 0;
         for ($BitrateRecordsCounter = 0; $BitrateRecordsCounter < $thisfile_asf_streambitrateproperties['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_streambitrateproperties['bitrate_records'][$BitrateRecordsCounter]['bitrate'];
                         break;
                     case 2:
                         $ASFbitrateAudio += $thisfile_asf_streambitrateproperties['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 self::$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 = Riff::RIFFparseWAVEFORMATex(substr($streamdata['type_specific_data'], $audiomediaoffset, 16));
                     $audiomediaoffset += 16;
                     $thisfile_audio['lossless'] = false;
                     switch ($thisfile_asf_audiomedia_currentstream['raw']['wFormatTag']) {
                         case 0x1:
                             // PCM
                         // PCM
                         case 0x163:
                             // WMA9 Lossless
                             $thisfile_audio['lossless'] = true;
                             break;
                     }
                     if (!empty($thisfile_asf['stream_bitrate_properties_object']['bitrate_records'])) {
                         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'] = Helper::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 self::$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'] = Helper::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 4));
                     $videomediaoffset += 4;
                     $thisfile_asf_videomedia_currentstream['image_height'] = Helper::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 4));
                     $videomediaoffset += 4;
                     $thisfile_asf_videomedia_currentstream['flags'] = Helper::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 1));
                     $videomediaoffset += 1;
                     $thisfile_asf_videomedia_currentstream['format_data_size'] = Helper::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 2));
                     $videomediaoffset += 2;
                     $thisfile_asf_videomedia_currentstream['format_data']['format_data_size'] = Helper::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 4));
                     $videomediaoffset += 4;
                     $thisfile_asf_videomedia_currentstream['format_data']['image_width'] = Helper::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 4));
                     $videomediaoffset += 4;
                     $thisfile_asf_videomedia_currentstream['format_data']['image_height'] = Helper::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 4));
                     $videomediaoffset += 4;
                     $thisfile_asf_videomedia_currentstream['format_data']['reserved'] = Helper::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 2));
                     $videomediaoffset += 2;
                     $thisfile_asf_videomedia_currentstream['format_data']['bits_per_pixel'] = Helper::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'] = Helper::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 4));
                     $videomediaoffset += 4;
                     $thisfile_asf_videomedia_currentstream['format_data']['horizontal_pels'] = Helper::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 4));
                     $videomediaoffset += 4;
                     $thisfile_asf_videomedia_currentstream['format_data']['vertical_pels'] = Helper::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 4));
                     $videomediaoffset += 4;
                     $thisfile_asf_videomedia_currentstream['format_data']['colors_used'] = Helper::LittleEndian2Int(substr($streamdata['type_specific_data'], $videomediaoffset, 4));
                     $videomediaoffset += 4;
                     $thisfile_asf_videomedia_currentstream['format_data']['colors_important'] = Helper::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'])) {
                         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'] = Riff::RIFFfourccLookup($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 (ftell($this->getid3->fp) < $info['avdataend']) {
         $NextObjectDataHeader = fread($this->getid3->fp, 24);
         $offset = 0;
         $NextObjectGUID = substr($NextObjectDataHeader, 0, 16);
         $offset += 16;
         $NextObjectGUIDtext = self::BytestringToGUID($NextObjectGUID);
         $NextObjectSize = Helper::LittleEndian2Int(substr($NextObjectDataHeader, $offset, 8));
         $offset += 8;
         switch ($NextObjectGUID) {
             case self::$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 . fread($this->getid3->fp, 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'] = self::BytestringToGUID($thisfile_asf_dataobject['fileid']);
                 $thisfile_asf_dataobject['total_data_packets'] = Helper::LittleEndian2Int(substr($DataObjectData, $offset, 8));
                 $offset += 8;
                 $thisfile_asf_dataobject['reserved'] = Helper::LittleEndian2Int(substr($DataObjectData, $offset, 2));
                 $offset += 2;
                 if ($thisfile_asf_dataobject['reserved'] != 0x101) {
                     $info['warning'][] = 'data_object.reserved (' . Helper::PrintHexBytes($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'] = ftell($this->getid3->fp);
                 fseek($this->getid3->fp, $thisfile_asf_dataobject['objectsize'] - 50, SEEK_CUR);
                 // skip actual audio/video data
                 $info['avdataend'] = ftell($this->getid3->fp);
                 break;
             case self::$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 . fread($this->getid3->fp, 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'] = self::BytestringToGUID($thisfile_asf_simpleindexobject['fileid']);
                 $thisfile_asf_simpleindexobject['index_entry_time_interval'] = Helper::LittleEndian2Int(substr($SimpleIndexObjectData, $offset, 8));
                 $offset += 8;
                 $thisfile_asf_simpleindexobject['maximum_packet_count'] = Helper::LittleEndian2Int(substr($SimpleIndexObjectData, $offset, 4));
                 $offset += 4;
                 $thisfile_asf_simpleindexobject['index_entries_count'] = Helper::LittleEndian2Int(substr($SimpleIndexObjectData, $offset, 4));
                 $offset += 4;
                 $IndexEntriesData = $SimpleIndexObjectData . fread($this->getid3->fp, 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'] = Helper::LittleEndian2Int(substr($IndexEntriesData, $offset, 4));
                     $offset += 4;
                     $thisfile_asf_simpleindexobject['index_entries'][$IndexEntriesCounter]['packet_count'] = Helper::LittleEndian2Int(substr($IndexEntriesData, $offset, 4));
                     $offset += 2;
                 }
                 break;
             case self::$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 . fread($this->getid3->fp, 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'] = Helper::LittleEndian2Int(substr($ASFIndexObjectData, $offset, 4));
                 $offset += 4;
                 $thisfile_asf_asfindexobject['index_specifiers_count'] = Helper::LittleEndian2Int(substr($ASFIndexObjectData, $offset, 2));
                 $offset += 2;
                 $thisfile_asf_asfindexobject['index_blocks_count'] = Helper::LittleEndian2Int(substr($ASFIndexObjectData, $offset, 4));
                 $offset += 4;
                 $ASFIndexObjectData .= fread($this->getid3->fp, 4 * $thisfile_asf_asfindexobject['index_specifiers_count']);
                 for ($IndexSpecifiersCounter = 0; $IndexSpecifiersCounter < $thisfile_asf_asfindexobject['index_specifiers_count']; ++$IndexSpecifiersCounter) {
                     $IndexSpecifierStreamNumber = Helper::LittleEndian2Int(substr($ASFIndexObjectData, $offset, 2));
                     $offset += 2;
                     $thisfile_asf_asfindexobject['index_specifiers'][$IndexSpecifiersCounter]['stream_number'] = $IndexSpecifierStreamNumber;
                     $thisfile_asf_asfindexobject['index_specifiers'][$IndexSpecifiersCounter]['index_type'] = Helper::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 .= fread($this->getid3->fp, 4);
                 $thisfile_asf_asfindexobject['index_entry_count'] = Helper::LittleEndian2Int(substr($ASFIndexObjectData, $offset, 4));
                 $offset += 4;
                 $ASFIndexObjectData .= fread($this->getid3->fp, 8 * $thisfile_asf_asfindexobject['index_specifiers_count']);
                 for ($IndexSpecifiersCounter = 0; $IndexSpecifiersCounter < $thisfile_asf_asfindexobject['index_specifiers_count']; ++$IndexSpecifiersCounter) {
                     $thisfile_asf_asfindexobject['block_positions'][$IndexSpecifiersCounter] = Helper::LittleEndian2Int(substr($ASFIndexObjectData, $offset, 8));
                     $offset += 8;
                 }
                 $ASFIndexObjectData .= fread($this->getid3->fp, 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] = Helper::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 (self::GUIDname($NextObjectGUIDtext)) {
                     $info['warning'][] = 'unhandled GUID "' . self::GUIDname($NextObjectGUIDtext) . '" {' . $NextObjectGUIDtext . '} in ASF body at offset ' . ($offset - 16 - 8);
                 } else {
                     $info['warning'][] = 'unknown GUID {' . $NextObjectGUIDtext . '} in ASF body at offset ' . (ftell($this->getid3->fp) - 16 - 8);
                 }
                 fseek($this->getid3->fp, $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(self::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(self::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'] = self::TrimConvert($thisfile_asf_codeclistobject['codec_entries'][$streamnumber]['name']);
                     break;
                 case 2:
                     // audio
                     $thisfile_audio['encoder'] = self::TrimConvert($thisfile_asf_codeclistobject['codec_entries'][$streamnumber]['name']);
                     // AH 2003-10-01
                     $thisfile_audio['encoder_options'] = self::TrimConvert($thisfile_asf_codeclistobject['codec_entries'][0]['description']);
                     $thisfile_audio['codec'] = $thisfile_audio['encoder'];
                     break;
                 default:
                     $info['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'] : (double) 1;
         $thisfile_video['dataformat'] = !empty($thisfile_video['dataformat']) ? $thisfile_video['dataformat'] : 'asf';
     }
     if (!empty($thisfile_video['streams'])) {
         $thisfile_video['streams']['resolution_x'] = 0;
         $thisfile_video['streams']['resolution_y'] = 0;
         foreach ($thisfile_video['streams'] as $key => $valuearray) {
             if ($valuearray['resolution_x'] > $thisfile_video['streams']['resolution_x'] || $valuearray['resolution_y'] > $thisfile_video['streams']['resolution_y']) {
                 $thisfile_video['resolution_x'] = $valuearray['resolution_x'];
                 $thisfile_video['resolution_y'] = $valuearray['resolution_y'];
             }
         }
     }
     $info['bitrate'] = (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;
 }
Пример #14
0
 public function RemoveID3v2()
 {
     // File MUST be writeable - CHMOD(646) at least. It's best if the
     // directory is also writeable, because that method is both faster and less susceptible to errors.
     if (is_writable(dirname($this->filename))) {
         // preferred method - only one copying operation, minimal chance of corrupting
         // original file if script is interrupted, but required directory to be writeable
         if (is_readable($this->filename) && is_file($this->filename) && ($fp_source = fopen($this->filename, 'rb'))) {
             // Initialize GetId3 engine
             $getID3 = new GetId3Core();
             $OldThisFileInfo = $getID3->analyze($this->filename);
             if (!Helper::intValueSupported($OldThisFileInfo['filesize'])) {
                 $this->errors[] = 'Unable to remove ID3v2 because file is larger than ' . round(PHP_INT_MAX / 1073741824) . 'GB';
                 fclose($fp_source);
                 return false;
             }
             rewind($fp_source);
             if ($OldThisFileInfo['avdataoffset'] !== false) {
                 fseek($fp_source, $OldThisFileInfo['avdataoffset'], SEEK_SET);
             }
             if (is_writable($this->filename) && is_file($this->filename) && ($fp_temp = fopen($this->filename . 'getid3tmp', 'w+b'))) {
                 while ($buffer = fread($fp_source, $this->fread_buffer_size)) {
                     fwrite($fp_temp, $buffer, strlen($buffer));
                 }
                 fclose($fp_temp);
             } else {
                 $this->errors[] = 'Could not fopen("' . $this->filename . 'getid3tmp", "w+b")';
             }
             fclose($fp_source);
         } else {
             $this->errors[] = 'Could not fopen("' . $this->filename . '", "rb")';
         }
         if (file_exists($this->filename)) {
             unlink($this->filename);
         }
         rename($this->filename . 'getid3tmp', $this->filename);
     } elseif (is_writable($this->filename)) {
         // less desirable alternate method - double-copies the file, overwrites original file
         // and could corrupt source file if the script is interrupted or an error occurs.
         if (is_readable($this->filename) && is_file($this->filename) && ($fp_source = fopen($this->filename, 'rb'))) {
             // Initialize GetId3 engine
             $getID3 = new GetId3Core();
             $OldThisFileInfo = $getID3->analyze($this->filename);
             if (!Helper::intValueSupported($OldThisFileInfo['filesize'])) {
                 $this->errors[] = 'Unable to remove ID3v2 because file is larger than ' . round(PHP_INT_MAX / 1073741824) . 'GB';
                 fclose($fp_source);
                 return false;
             }
             rewind($fp_source);
             if ($OldThisFileInfo['avdataoffset'] !== false) {
                 fseek($fp_source, $OldThisFileInfo['avdataoffset'], SEEK_SET);
             }
             if ($fp_temp = tmpfile()) {
                 while ($buffer = fread($fp_source, $this->fread_buffer_size)) {
                     fwrite($fp_temp, $buffer, strlen($buffer));
                 }
                 fclose($fp_source);
                 if (is_writable($this->filename) && is_file($this->filename) && ($fp_source = fopen($this->filename, 'wb'))) {
                     rewind($fp_temp);
                     while ($buffer = fread($fp_temp, $this->fread_buffer_size)) {
                         fwrite($fp_source, $buffer, strlen($buffer));
                     }
                     fseek($fp_temp, -128, SEEK_END);
                     fclose($fp_source);
                 } else {
                     $this->errors[] = 'Could not fopen("' . $this->filename . '", "wb")';
                 }
                 fclose($fp_temp);
             } else {
                 $this->errors[] = 'Could not create tmpfile()';
             }
         } else {
             $this->errors[] = 'Could not fopen("' . $this->filename . '", "rb")';
         }
     } else {
         $this->errors[] = 'Directory and file both not writeable';
     }
     if (!empty($this->errors)) {
         return false;
     }
     return true;
 }
Пример #15
0
 /**
  * @return bool
  */
 public function analyze()
 {
     $info =& $this->getid3->info;
     $info['fileformat'] = 'jpg';
     $info['video']['dataformat'] = 'jpg';
     $info['video']['lossless'] = false;
     $info['video']['bits_per_sample'] = 24;
     $info['video']['pixel_aspect_ratio'] = (double) 1;
     fseek($this->getid3->fp, $info['avdataoffset'], SEEK_SET);
     $imageinfo = array();
     list($width, $height, $type) = Helper::GetDataImageSize(fread($this->getid3->fp, $info['filesize']), $imageinfo);
     if (isset($imageinfo['APP13'])) {
         // http://php.net/iptcparse
         // http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/IPTC.html
         $iptc_parsed = iptcparse($imageinfo['APP13']);
         if (is_array($iptc_parsed)) {
             foreach ($iptc_parsed as $iptc_key_raw => $iptc_values) {
                 list($iptc_record, $iptc_tagkey) = explode('#', $iptc_key_raw);
                 $iptc_tagkey = intval(ltrim($iptc_tagkey, '0'));
                 foreach ($iptc_values as $key => $value) {
                     $IPTCrecordName = $this->IPTCrecordName($iptc_record);
                     $IPTCrecordTagName = $this->IPTCrecordTagName($iptc_record, $iptc_tagkey);
                     if (isset($info['iptc'][$IPTCrecordName][$IPTCrecordTagName])) {
                         $info['iptc'][$IPTCrecordName][$IPTCrecordTagName][] = $value;
                     } else {
                         $info['iptc'][$IPTCrecordName][$IPTCrecordTagName] = array($value);
                     }
                 }
             }
         }
     }
     $returnOK = false;
     switch ($type) {
         case IMG_JPG:
             $info['video']['resolution_x'] = $width;
             $info['video']['resolution_y'] = $height;
             if (isset($imageinfo['APP1'])) {
                 if (function_exists('exif_read_data')) {
                     if (substr($imageinfo['APP1'], 0, 4) == 'Exif') {
                         $info['jpg']['exif'] = @exif_read_data($info['filenamepath'], '', true, false);
                     } else {
                         $info['warning'][] = 'exif_read_data() cannot parse non-EXIF data in APP1 (expected "Exif", found "' . substr($imageinfo['APP1'], 0, 4) . '")';
                     }
                 } else {
                     $info['warning'][] = 'EXIF parsing only available when ' . (GetId3Core::environmentIsWindows() ? 'php_exif.dll enabled' : 'compiled with --enable-exif');
                 }
             }
             $returnOK = true;
             break;
         default:
             break;
     }
     $cast_as_appropriate_keys = array('EXIF', 'IFD0', 'THUMBNAIL');
     foreach ($cast_as_appropriate_keys as $exif_key) {
         if (isset($info['jpg']['exif'][$exif_key])) {
             foreach ($info['jpg']['exif'][$exif_key] as $key => $value) {
                 $info['jpg']['exif'][$exif_key][$key] = $this->CastAsAppropriate($value);
             }
         }
     }
     if (isset($info['jpg']['exif']['GPS'])) {
         if (isset($info['jpg']['exif']['GPS']['GPSVersion'])) {
             for ($i = 0; $i < 4; ++$i) {
                 $version_subparts[$i] = ord(substr($info['jpg']['exif']['GPS']['GPSVersion'], $i, 1));
             }
             $info['jpg']['exif']['GPS']['computed']['version'] = 'v' . implode('.', $version_subparts);
         }
         if (isset($info['jpg']['exif']['GPS']['GPSDateStamp'])) {
             $explodedGPSDateStamp = explode(':', $info['jpg']['exif']['GPS']['GPSDateStamp']);
             $computed_time[5] = isset($explodedGPSDateStamp[0]) ? $explodedGPSDateStamp[0] : '';
             $computed_time[3] = isset($explodedGPSDateStamp[1]) ? $explodedGPSDateStamp[1] : '';
             $computed_time[4] = isset($explodedGPSDateStamp[2]) ? $explodedGPSDateStamp[2] : '';
             if (function_exists('date_default_timezone_set')) {
                 date_default_timezone_set('UTC');
             } else {
                 ini_set('date.timezone', 'UTC');
             }
             $computed_time = array(0 => 0, 1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0);
             if (isset($info['jpg']['exif']['GPS']['GPSTimeStamp']) && is_array($info['jpg']['exif']['GPS']['GPSTimeStamp'])) {
                 foreach ($info['jpg']['exif']['GPS']['GPSTimeStamp'] as $key => $value) {
                     $computed_time[$key] = Helper::DecimalizeFraction($value);
                 }
             }
             $info['jpg']['exif']['GPS']['computed']['timestamp'] = mktime($computed_time[0], $computed_time[1], $computed_time[2], $computed_time[3], $computed_time[4], $computed_time[5]);
         }
         if (isset($info['jpg']['exif']['GPS']['GPSLatitude']) && is_array($info['jpg']['exif']['GPS']['GPSLatitude'])) {
             $direction_multiplier = isset($info['jpg']['exif']['GPS']['GPSLatitudeRef']) && $info['jpg']['exif']['GPS']['GPSLatitudeRef'] == 'S' ? -1 : 1;
             foreach ($info['jpg']['exif']['GPS']['GPSLatitude'] as $key => $value) {
                 $computed_latitude[$key] = Helper::DecimalizeFraction($value);
             }
             $info['jpg']['exif']['GPS']['computed']['latitude'] = $direction_multiplier * ($computed_latitude[0] + $computed_latitude[1] / 60 + $computed_latitude[2] / 3600);
         }
         if (isset($info['jpg']['exif']['GPS']['GPSLongitude']) && is_array($info['jpg']['exif']['GPS']['GPSLongitude'])) {
             $direction_multiplier = isset($info['jpg']['exif']['GPS']['GPSLongitudeRef']) && $info['jpg']['exif']['GPS']['GPSLongitudeRef'] == 'W' ? -1 : 1;
             foreach ($info['jpg']['exif']['GPS']['GPSLongitude'] as $key => $value) {
                 $computed_longitude[$key] = Helper::DecimalizeFraction($value);
             }
             $info['jpg']['exif']['GPS']['computed']['longitude'] = $direction_multiplier * ($computed_longitude[0] + $computed_longitude[1] / 60 + $computed_longitude[2] / 3600);
         }
         if (isset($info['jpg']['exif']['GPS']['GPSAltitude'])) {
             $direction_multiplier = isset($info['jpg']['exif']['GPS']['GPSAltitudeRef']) && $info['jpg']['exif']['GPS']['GPSAltitudeRef'] === chr(1) ? -1 : 1;
             $info['jpg']['exif']['GPS']['computed']['altitude'] = $direction_multiplier * Helper::DecimalizeFraction($info['jpg']['exif']['GPS']['GPSAltitude']);
         }
     }
     if (class_exists('Helpers\\GetId3\\Module\\Tag\\Xmp')) {
         if (isset($info['filenamepath'])) {
             $image_xmp = new Xmp($info['filenamepath']);
             $xmp_raw = $image_xmp->getAllTags();
             foreach ($xmp_raw as $key => $value) {
                 list($subsection, $tagname) = explode(':', $key);
                 $info['xmp'][$subsection][$tagname] = $this->CastAsAppropriate($value);
             }
         }
     }
     if (!$returnOK) {
         unset($info['fileformat']);
         return false;
     }
     return true;
 }
Пример #16
0
 /**
  * @param  type    $RIFFdata
  *
  * @return bool
  */
 public function ParseRIFFdata(&$RIFFdata)
 {
     $info =& $this->getid3->info;
     if ($RIFFdata) {
         $tempfile = tempnam(GetId3Core::getTempDir(), 'getID3');
         $fp_temp = fopen($tempfile, 'wb');
         $RIFFdataLength = strlen($RIFFdata);
         $NewLengthString = Helper::LittleEndian2String($RIFFdataLength, 4);
         for ($i = 0; $i < 4; ++$i) {
             $RIFFdata[$i + 4] = $NewLengthString[$i];
         }
         fwrite($fp_temp, $RIFFdata);
         fclose($fp_temp);
         $getid3_temp = new GetId3Core();
         $getid3_temp->openfile($tempfile);
         $getid3_temp->info['filesize'] = $RIFFdataLength;
         $getid3_temp->info['filenamepath'] = $info['filenamepath'];
         $getid3_temp->info['tags'] = $info['tags'];
         $getid3_temp->info['warning'] = $info['warning'];
         $getid3_temp->info['error'] = $info['error'];
         $getid3_temp->info['comments'] = $info['comments'];
         $getid3_temp->info['audio'] = isset($info['audio']) ? $info['audio'] : array();
         $getid3_temp->info['video'] = isset($info['video']) ? $info['video'] : array();
         $getid3_riff = new self($getid3_temp);
         $getid3_riff->analyze();
         $info['riff'] = $getid3_temp->info['riff'];
         $info['warning'] = $getid3_temp->info['warning'];
         $info['error'] = $getid3_temp->info['error'];
         $info['tags'] = $getid3_temp->info['tags'];
         $info['comments'] = $getid3_temp->info['comments'];
         unset($getid3_riff, $getid3_temp);
         unlink($tempfile);
     }
     return false;
 }
Пример #17
0
 /**
  * @return bool
  */
 public function DeleteAPEtag()
 {
     $getID3 = new GetId3Core();
     $ThisFileInfo = $getID3->analyze($this->filename);
     if (isset($ThisFileInfo['ape']['tag_offset_start']) && isset($ThisFileInfo['ape']['tag_offset_end'])) {
         if (is_writable($this->filename) && is_file($this->filename) && ($fp = fopen($this->filename, 'a+b'))) {
             flock($fp, LOCK_EX);
             $oldignoreuserabort = ignore_user_abort(true);
             fseek($fp, $ThisFileInfo['ape']['tag_offset_end'], SEEK_SET);
             $DataAfterAPE = '';
             if ($ThisFileInfo['filesize'] > $ThisFileInfo['ape']['tag_offset_end']) {
                 $DataAfterAPE = fread($fp, $ThisFileInfo['filesize'] - $ThisFileInfo['ape']['tag_offset_end']);
             }
             ftruncate($fp, $ThisFileInfo['ape']['tag_offset_start']);
             fseek($fp, $ThisFileInfo['ape']['tag_offset_start'], SEEK_SET);
             if (!empty($DataAfterAPE)) {
                 fwrite($fp, $DataAfterAPE, strlen($DataAfterAPE));
             }
             flock($fp, LOCK_UN);
             fclose($fp);
             ignore_user_abort($oldignoreuserabort);
             return true;
         }
         return false;
     }
     return true;
 }
Пример #18
0
 /**
  * @return bool
  */
 public function analyze()
 {
     $info =& $this->getid3->info;
     $offset = 0;
     fseek($this->getid3->fp, $info['avdataoffset'], SEEK_SET);
     $rawdata = fread($this->getid3->fp, $this->getid3->fread_buffer_size());
     switch (substr($rawdata, $offset, 4)) {
         case 'LA02':
         case 'LA03':
         case 'LA04':
             $info['fileformat'] = 'la';
             $info['audio']['dataformat'] = 'la';
             $info['audio']['lossless'] = true;
             $info['la']['version_major'] = (int) substr($rawdata, $offset + 2, 1);
             $info['la']['version_minor'] = (int) substr($rawdata, $offset + 3, 1);
             $info['la']['version'] = (double) $info['la']['version_major'] + $info['la']['version_minor'] / 10;
             $offset += 4;
             $info['la']['uncompressed_size'] = Helper::LittleEndian2Int(substr($rawdata, $offset, 4));
             $offset += 4;
             if ($info['la']['uncompressed_size'] == 0) {
                 $info['error'][] = 'Corrupt LA file: uncompressed_size == zero';
                 return false;
             }
             $WAVEchunk = substr($rawdata, $offset, 4);
             if ($WAVEchunk !== 'WAVE') {
                 $info['error'][] = 'Expected "WAVE" (' . Helper::PrintHexBytes('WAVE') . ') at offset ' . $offset . ', found "' . $WAVEchunk . '" (' . Helper::PrintHexBytes($WAVEchunk) . ') instead.';
                 return false;
             }
             $offset += 4;
             $info['la']['fmt_size'] = 24;
             if ($info['la']['version'] >= 0.3) {
                 $info['la']['fmt_size'] = Helper::LittleEndian2Int(substr($rawdata, $offset, 4));
                 $info['la']['header_size'] = 49 + $info['la']['fmt_size'] - 24;
                 $offset += 4;
             } else {
                 // version 0.2 didn't support additional data blocks
                 $info['la']['header_size'] = 41;
             }
             $fmt_chunk = substr($rawdata, $offset, 4);
             if ($fmt_chunk !== 'fmt ') {
                 $info['error'][] = 'Expected "fmt " (' . Helper::PrintHexBytes('fmt ') . ') at offset ' . $offset . ', found "' . $fmt_chunk . '" (' . Helper::PrintHexBytes($fmt_chunk) . ') instead.';
                 return false;
             }
             $offset += 4;
             $fmt_size = Helper::LittleEndian2Int(substr($rawdata, $offset, 4));
             $offset += 4;
             $info['la']['raw']['format'] = Helper::LittleEndian2Int(substr($rawdata, $offset, 2));
             $offset += 2;
             $info['la']['channels'] = Helper::LittleEndian2Int(substr($rawdata, $offset, 2));
             $offset += 2;
             if ($info['la']['channels'] == 0) {
                 $info['error'][] = 'Corrupt LA file: channels == zero';
                 return false;
             }
             $info['la']['sample_rate'] = Helper::LittleEndian2Int(substr($rawdata, $offset, 4));
             $offset += 4;
             if ($info['la']['sample_rate'] == 0) {
                 $info['error'][] = 'Corrupt LA file: sample_rate == zero';
                 return false;
             }
             $info['la']['bytes_per_second'] = Helper::LittleEndian2Int(substr($rawdata, $offset, 4));
             $offset += 4;
             $info['la']['bytes_per_sample'] = Helper::LittleEndian2Int(substr($rawdata, $offset, 2));
             $offset += 2;
             $info['la']['bits_per_sample'] = Helper::LittleEndian2Int(substr($rawdata, $offset, 2));
             $offset += 2;
             $info['la']['samples'] = Helper::LittleEndian2Int(substr($rawdata, $offset, 4));
             $offset += 4;
             $info['la']['raw']['flags'] = Helper::LittleEndian2Int(substr($rawdata, $offset, 1));
             $offset += 1;
             $info['la']['flags']['seekable'] = (bool) ($info['la']['raw']['flags'] & 0x1);
             if ($info['la']['version'] >= 0.4) {
                 $info['la']['flags']['high_compression'] = (bool) ($info['la']['raw']['flags'] & 0x2);
             }
             $info['la']['original_crc'] = Helper::LittleEndian2Int(substr($rawdata, $offset, 4));
             $offset += 4;
             // mikeØbevin*de
             // Basically, the blocksize/seekevery are 61440/19 in La0.4 and 73728/16
             // in earlier versions. A seekpoint is added every blocksize * seekevery
             // samples, so 4 * int(totalSamples / (blockSize * seekEvery)) should
             // give the number of bytes used for the seekpoints. Of course, if seeking
             // is disabled, there are no seekpoints stored.
             if ($info['la']['version'] >= 0.4) {
                 $info['la']['blocksize'] = 61440;
                 $info['la']['seekevery'] = 19;
             } else {
                 $info['la']['blocksize'] = 73728;
                 $info['la']['seekevery'] = 16;
             }
             $info['la']['seekpoint_count'] = 0;
             if ($info['la']['flags']['seekable']) {
                 $info['la']['seekpoint_count'] = floor($info['la']['samples'] / ($info['la']['blocksize'] * $info['la']['seekevery']));
                 for ($i = 0; $i < $info['la']['seekpoint_count']; ++$i) {
                     $info['la']['seekpoints'][] = Helper::LittleEndian2Int(substr($rawdata, $offset, 4));
                     $offset += 4;
                 }
             }
             if ($info['la']['version'] >= 0.3) {
                 // Following the main header information, the program outputs all of the
                 // seekpoints. Following these is what I called the 'footer start',
                 // i.e. the position immediately after the La audio data is finished.
                 $info['la']['footerstart'] = Helper::LittleEndian2Int(substr($rawdata, $offset, 4));
                 $offset += 4;
                 if ($info['la']['footerstart'] > $info['filesize']) {
                     $info['warning'][] = 'FooterStart value points to offset ' . $info['la']['footerstart'] . ' which is beyond end-of-file (' . $info['filesize'] . ')';
                     $info['la']['footerstart'] = $info['filesize'];
                 }
             } else {
                 // La v0.2 didn't have FooterStart value
                 $info['la']['footerstart'] = $info['avdataend'];
             }
             if ($info['la']['footerstart'] < $info['avdataend']) {
                 if ($RIFFtempfilename = tempnam(GetId3Core::getTempDir(), 'id3')) {
                     if ($RIFF_fp = fopen($RIFFtempfilename, 'w+b')) {
                         $RIFFdata = 'WAVE';
                         if ($info['la']['version'] == 0.2) {
                             $RIFFdata .= substr($rawdata, 12, 24);
                         } else {
                             $RIFFdata .= substr($rawdata, 16, 24);
                         }
                         if ($info['la']['footerstart'] < $info['avdataend']) {
                             fseek($this->getid3->fp, $info['la']['footerstart'], SEEK_SET);
                             $RIFFdata .= fread($this->getid3->fp, $info['avdataend'] - $info['la']['footerstart']);
                         }
                         $RIFFdata = 'RIFF' . Helper::LittleEndian2String(strlen($RIFFdata), 4, false) . $RIFFdata;
                         fwrite($RIFF_fp, $RIFFdata, strlen($RIFFdata));
                         fclose($RIFF_fp);
                         $getid3_temp = new GetId3Core();
                         $getid3_temp->openfile($RIFFtempfilename);
                         $getid3_riff = new Riff($getid3_temp);
                         $getid3_riff->analyze();
                         if (empty($getid3_temp->info['error'])) {
                             $info['riff'] = $getid3_temp->info['riff'];
                         } else {
                             $info['warning'][] = 'Error parsing RIFF portion of La file: ' . implode($getid3_temp->info['error']);
                         }
                         unset($getid3_temp, $getid3_riff);
                     }
                     unlink($RIFFtempfilename);
                 }
             }
             // $info['avdataoffset'] should be zero to begin with, but just in case it's not, include the addition anyway
             $info['avdataend'] = $info['avdataoffset'] + $info['la']['footerstart'];
             $info['avdataoffset'] = $info['avdataoffset'] + $offset;
             //$info['la']['codec']                = RIFFwFormatTagLookup($info['la']['raw']['format']);
             $info['la']['compression_ratio'] = (double) (($info['avdataend'] - $info['avdataoffset']) / $info['la']['uncompressed_size']);
             $info['playtime_seconds'] = (double) ($info['la']['samples'] / $info['la']['sample_rate']) / $info['la']['channels'];
             if ($info['playtime_seconds'] == 0) {
                 $info['error'][] = 'Corrupt LA file: playtime_seconds == zero';
                 return false;
             }
             $info['audio']['bitrate'] = ($info['avdataend'] - $info['avdataoffset']) * 8 / $info['playtime_seconds'];
             //$info['audio']['codec']              = $info['la']['codec'];
             $info['audio']['bits_per_sample'] = $info['la']['bits_per_sample'];
             break;
         default:
             if (substr($rawdata, $offset, 2) == 'LA') {
                 $info['error'][] = 'This version of GetId3Core() [' . $this->getid3->version() . '] does not support LA version ' . substr($rawdata, $offset + 2, 1) . '.' . substr($rawdata, $offset + 3, 1) . ' which this appears to be - check http://getid3.sourceforge.net for updates.';
             } else {
                 $info['error'][] = 'Not a LA (Lossless-Audio) file';
             }
             return false;
             break;
     }
     $info['audio']['channels'] = $info['la']['channels'];
     $info['audio']['sample_rate'] = (int) $info['la']['sample_rate'];
     $info['audio']['encoder'] = 'LA v' . $info['la']['version'];
     return true;
 }
Пример #19
0
 /**
  * @return bool
  */
 public function ParseOptimFROGheader45()
 {
     // for fileformat of v4.50a and higher
     $info =& $this->getid3->info;
     $RIFFdata = '';
     fseek($this->getid3->fp, $info['avdataoffset'], SEEK_SET);
     while (!feof($this->getid3->fp) && ftell($this->getid3->fp) < $info['avdataend']) {
         $BlockOffset = ftell($this->getid3->fp);
         $BlockData = fread($this->getid3->fp, 8);
         $offset = 8;
         $BlockName = substr($BlockData, 0, 4);
         $BlockSize = Helper::LittleEndian2Int(substr($BlockData, 4, 4));
         if ($BlockName == 'OFRX') {
             $BlockName = 'OFR ';
         }
         if (!isset($info['ofr'][$BlockName])) {
             $info['ofr'][$BlockName] = array();
         }
         $thisfile_ofr_thisblock =& $info['ofr'][$BlockName];
         switch ($BlockName) {
             case 'OFR ':
                 // shortcut
                 $thisfile_ofr_thisblock['offset'] = $BlockOffset;
                 $thisfile_ofr_thisblock['size'] = $BlockSize;
                 $info['audio']['encoder'] = 'OptimFROG 4.50 alpha';
                 switch ($BlockSize) {
                     case 12:
                     case 15:
                         // good
                         break;
                     default:
                         $info['warning'][] = '"' . $BlockName . '" contains more data than expected (expected 12 or 15 bytes, found ' . $BlockSize . ' bytes)';
                         break;
                 }
                 $BlockData .= fread($this->getid3->fp, $BlockSize);
                 $thisfile_ofr_thisblock['total_samples'] = Helper::LittleEndian2Int(substr($BlockData, $offset, 6));
                 $offset += 6;
                 $thisfile_ofr_thisblock['raw']['sample_type'] = Helper::LittleEndian2Int(substr($BlockData, $offset, 1));
                 $thisfile_ofr_thisblock['sample_type'] = $this->OptimFROGsampleTypeLookup($thisfile_ofr_thisblock['raw']['sample_type']);
                 $offset += 1;
                 $thisfile_ofr_thisblock['channel_config'] = Helper::LittleEndian2Int(substr($BlockData, $offset, 1));
                 $thisfile_ofr_thisblock['channels'] = $thisfile_ofr_thisblock['channel_config'];
                 $offset += 1;
                 $thisfile_ofr_thisblock['sample_rate'] = Helper::LittleEndian2Int(substr($BlockData, $offset, 4));
                 $offset += 4;
                 if ($BlockSize > 12) {
                     // OFR 4.504b or higher
                     $thisfile_ofr_thisblock['channels'] = $this->OptimFROGchannelConfigNumChannelsLookup($thisfile_ofr_thisblock['channel_config']);
                     $thisfile_ofr_thisblock['raw']['encoder_id'] = Helper::LittleEndian2Int(substr($BlockData, $offset, 2));
                     $thisfile_ofr_thisblock['encoder'] = $this->OptimFROGencoderNameLookup($thisfile_ofr_thisblock['raw']['encoder_id']);
                     $offset += 2;
                     $thisfile_ofr_thisblock['raw']['compression'] = Helper::LittleEndian2Int(substr($BlockData, $offset, 1));
                     $thisfile_ofr_thisblock['compression'] = $this->OptimFROGcompressionLookup($thisfile_ofr_thisblock['raw']['compression']);
                     $thisfile_ofr_thisblock['speedup'] = $this->OptimFROGspeedupLookup($thisfile_ofr_thisblock['raw']['compression']);
                     $offset += 1;
                     $info['audio']['encoder'] = 'OptimFROG ' . $thisfile_ofr_thisblock['encoder'];
                     $info['audio']['encoder_options'] = '--mode ' . $thisfile_ofr_thisblock['compression'];
                     if (($thisfile_ofr_thisblock['raw']['encoder_id'] & 0xf0) >> 4 == 7) {
                         // v4.507
                         if (strtolower(Helper::fileextension($info['filename'])) == 'ofs') {
                             // OptimFROG DualStream format is lossy, but as of v4.507 there is no way to tell the difference
                             // between lossless and lossy other than the file extension.
                             $info['audio']['dataformat'] = 'ofs';
                             $info['audio']['lossless'] = true;
                         }
                     }
                 }
                 $info['audio']['channels'] = $thisfile_ofr_thisblock['channels'];
                 $info['audio']['sample_rate'] = $thisfile_ofr_thisblock['sample_rate'];
                 $info['audio']['bits_per_sample'] = $this->OptimFROGbitsPerSampleTypeLookup($thisfile_ofr_thisblock['raw']['sample_type']);
                 break;
             case 'COMP':
                 // unlike other block types, there CAN be multiple COMP blocks
                 $COMPdata['offset'] = $BlockOffset;
                 $COMPdata['size'] = $BlockSize;
                 if ($info['avdataoffset'] == 0) {
                     $info['avdataoffset'] = $BlockOffset;
                 }
                 // Only interested in first 14 bytes (only first 12 needed for v4.50 alpha), not actual audio data
                 $BlockData .= fread($this->getid3->fp, 14);
                 fseek($this->getid3->fp, $BlockSize - 14, SEEK_CUR);
                 $COMPdata['crc_32'] = Helper::LittleEndian2Int(substr($BlockData, $offset, 4));
                 $offset += 4;
                 $COMPdata['sample_count'] = Helper::LittleEndian2Int(substr($BlockData, $offset, 4));
                 $offset += 4;
                 $COMPdata['raw']['sample_type'] = Helper::LittleEndian2Int(substr($BlockData, $offset, 1));
                 $COMPdata['sample_type'] = $this->OptimFROGsampleTypeLookup($COMPdata['raw']['sample_type']);
                 $offset += 1;
                 $COMPdata['raw']['channel_configuration'] = Helper::LittleEndian2Int(substr($BlockData, $offset, 1));
                 $COMPdata['channel_configuration'] = $this->OptimFROGchannelConfigurationLookup($COMPdata['raw']['channel_configuration']);
                 $offset += 1;
                 $COMPdata['raw']['algorithm_id'] = Helper::LittleEndian2Int(substr($BlockData, $offset, 2));
                 //$COMPdata['algorithm']                    = OptimFROGalgorithmNameLookup($COMPdata['raw']['algorithm_id']);
                 $offset += 2;
                 if ($info['ofr']['OFR ']['size'] > 12) {
                     // OFR 4.504b or higher
                     $COMPdata['raw']['encoder_id'] = Helper::LittleEndian2Int(substr($BlockData, $offset, 2));
                     $COMPdata['encoder'] = $this->OptimFROGencoderNameLookup($COMPdata['raw']['encoder_id']);
                     $offset += 2;
                 }
                 if ($COMPdata['crc_32'] == 0x454e4f4e) {
                     // ASCII value of 'NONE' - placeholder value in v4.50a
                     $COMPdata['crc_32'] = false;
                 }
                 $thisfile_ofr_thisblock[] = $COMPdata;
                 break;
             case 'HEAD':
                 $thisfile_ofr_thisblock['offset'] = $BlockOffset;
                 $thisfile_ofr_thisblock['size'] = $BlockSize;
                 $RIFFdata .= fread($this->getid3->fp, $BlockSize);
                 break;
             case 'TAIL':
                 $thisfile_ofr_thisblock['offset'] = $BlockOffset;
                 $thisfile_ofr_thisblock['size'] = $BlockSize;
                 if ($BlockSize > 0) {
                     $RIFFdata .= fread($this->getid3->fp, $BlockSize);
                 }
                 break;
             case 'RECV':
                 // block contains no useful meta data - simply note and skip
                 $thisfile_ofr_thisblock['offset'] = $BlockOffset;
                 $thisfile_ofr_thisblock['size'] = $BlockSize;
                 fseek($this->getid3->fp, $BlockSize, SEEK_CUR);
                 break;
             case 'APET':
                 // APEtag v2
                 $thisfile_ofr_thisblock['offset'] = $BlockOffset;
                 $thisfile_ofr_thisblock['size'] = $BlockSize;
                 $info['warning'][] = 'APEtag processing inside OptimFROG not supported in this version (' . $this->getid3->version() . ') of GetId3Core()';
                 fseek($this->getid3->fp, $BlockSize, SEEK_CUR);
                 break;
             case 'MD5 ':
                 // APEtag v2
                 $thisfile_ofr_thisblock['offset'] = $BlockOffset;
                 $thisfile_ofr_thisblock['size'] = $BlockSize;
                 if ($BlockSize == 16) {
                     $thisfile_ofr_thisblock['md5_binary'] = fread($this->getid3->fp, $BlockSize);
                     $thisfile_ofr_thisblock['md5_string'] = Helper::PrintHexBytes($thisfile_ofr_thisblock['md5_binary'], true, false, false);
                     $info['md5_data_source'] = $thisfile_ofr_thisblock['md5_string'];
                 } else {
                     $info['warning'][] = 'Expecting block size of 16 in "MD5 " chunk, found ' . $BlockSize . ' instead';
                     fseek($this->getid3->fp, $BlockSize, SEEK_CUR);
                 }
                 break;
             default:
                 $thisfile_ofr_thisblock['offset'] = $BlockOffset;
                 $thisfile_ofr_thisblock['size'] = $BlockSize;
                 $info['warning'][] = 'Unhandled OptimFROG block type "' . $BlockName . '" at offset ' . $thisfile_ofr_thisblock['offset'];
                 fseek($this->getid3->fp, $BlockSize, SEEK_CUR);
                 break;
         }
     }
     if (isset($info['ofr']['TAIL']['offset'])) {
         $info['avdataend'] = $info['ofr']['TAIL']['offset'];
     }
     $info['playtime_seconds'] = (double) $info['ofr']['OFR ']['total_samples'] / ($info['audio']['channels'] * $info['audio']['sample_rate']);
     $info['audio']['bitrate'] = ($info['avdataend'] - $info['avdataoffset']) * 8 / $info['playtime_seconds'];
     // move the data chunk after all other chunks (if any)
     // so that the RIFF parser doesn't see EOF when trying
     // to skip over the data chunk
     $RIFFdata = substr($RIFFdata, 0, 36) . substr($RIFFdata, 44) . substr($RIFFdata, 36, 8);
     $getid3_temp = new GetId3Core();
     $getid3_temp->openfile($this->getid3->filename);
     $getid3_temp->info['avdataoffset'] = $info['avdataoffset'];
     $getid3_temp->info['avdataend'] = $info['avdataend'];
     $getid3_riff = new Riff($getid3_temp);
     $getid3_riff->ParseRIFFdata($RIFFdata);
     $info['riff'] = $getid3_temp->info['riff'];
     unset($getid3_riff, $getid3_temp, $RIFFdata);
     return true;
 }
Пример #20
0
 /**
  * @return bool
  */
 public function analyze()
 {
     $info =& $this->getid3->info;
     if ($info['avdataend'] <= $info['avdataoffset']) {
         $info['error'][] = '"avdataend" (' . $info['avdataend'] . ') is unexpectedly less-than-or-equal-to "avdataoffset" (' . $info['avdataoffset'] . ')';
         return false;
     }
     $info['fileformat'] = 'mpeg';
     fseek($this->getid3->fp, $info['avdataoffset'], SEEK_SET);
     $MPEGstreamData = fread($this->getid3->fp, min(100000, $info['avdataend'] - $info['avdataoffset']));
     $MPEGstreamDataLength = strlen($MPEGstreamData);
     $foundVideo = true;
     $VideoChunkOffset = 0;
     while (substr($MPEGstreamData, $VideoChunkOffset++, 4) !== self::GETID3_MPEG_VIDEO_SEQUENCE_HEADER) {
         if ($VideoChunkOffset >= $MPEGstreamDataLength) {
             $foundVideo = false;
             break;
         }
     }
     if ($foundVideo) {
         // Start code                       32 bits
         // horizontal frame size            12 bits
         // vertical frame size              12 bits
         // pixel aspect ratio                4 bits
         // frame rate                        4 bits
         // bitrate                          18 bits
         // marker bit                        1 bit
         // VBV buffer size                  10 bits
         // constrained parameter flag        1 bit
         // intra quant. matrix flag          1 bit
         // intra quant. matrix values      512 bits (present if matrix flag == 1)
         // non-intra quant. matrix flag      1 bit
         // non-intra quant. matrix values  512 bits (present if matrix flag == 1)
         $info['video']['dataformat'] = 'mpeg';
         $VideoChunkOffset += strlen(self::GETID3_MPEG_VIDEO_SEQUENCE_HEADER) - 1;
         $FrameSizeDWORD = Helper::BigEndian2Int(substr($MPEGstreamData, $VideoChunkOffset, 3));
         $VideoChunkOffset += 3;
         $AspectRatioFrameRateDWORD = Helper::BigEndian2Int(substr($MPEGstreamData, $VideoChunkOffset, 1));
         $VideoChunkOffset += 1;
         $assortedinformation = Helper::BigEndian2Bin(substr($MPEGstreamData, $VideoChunkOffset, 4));
         $VideoChunkOffset += 4;
         $info['mpeg']['video']['raw']['framesize_horizontal'] = ($FrameSizeDWORD & 0xfff000) >> 12;
         // 12 bits for horizontal frame size
         $info['mpeg']['video']['raw']['framesize_vertical'] = $FrameSizeDWORD & 0xfff;
         // 12 bits for vertical frame size
         $info['mpeg']['video']['raw']['pixel_aspect_ratio'] = ($AspectRatioFrameRateDWORD & 0xf0) >> 4;
         $info['mpeg']['video']['raw']['frame_rate'] = $AspectRatioFrameRateDWORD & 0xf;
         $info['mpeg']['video']['framesize_horizontal'] = $info['mpeg']['video']['raw']['framesize_horizontal'];
         $info['mpeg']['video']['framesize_vertical'] = $info['mpeg']['video']['raw']['framesize_vertical'];
         $info['mpeg']['video']['pixel_aspect_ratio'] = $this->MPEGvideoAspectRatioLookup($info['mpeg']['video']['raw']['pixel_aspect_ratio']);
         $info['mpeg']['video']['pixel_aspect_ratio_text'] = $this->MPEGvideoAspectRatioTextLookup($info['mpeg']['video']['raw']['pixel_aspect_ratio']);
         $info['mpeg']['video']['frame_rate'] = $this->MPEGvideoFramerateLookup($info['mpeg']['video']['raw']['frame_rate']);
         $info['mpeg']['video']['raw']['bitrate'] = Helper::Bin2Dec(substr($assortedinformation, 0, 18));
         $info['mpeg']['video']['raw']['marker_bit'] = (bool) Helper::Bin2Dec(substr($assortedinformation, 18, 1));
         $info['mpeg']['video']['raw']['vbv_buffer_size'] = Helper::Bin2Dec(substr($assortedinformation, 19, 10));
         $info['mpeg']['video']['raw']['constrained_param_flag'] = (bool) Helper::Bin2Dec(substr($assortedinformation, 29, 1));
         $info['mpeg']['video']['raw']['intra_quant_flag'] = (bool) Helper::Bin2Dec(substr($assortedinformation, 30, 1));
         if ($info['mpeg']['video']['raw']['intra_quant_flag']) {
             // read 512 bits
             $info['mpeg']['video']['raw']['intra_quant'] = Helper::BigEndian2Bin(substr($MPEGstreamData, $VideoChunkOffset, 64));
             $VideoChunkOffset += 64;
             $info['mpeg']['video']['raw']['non_intra_quant_flag'] = (bool) Helper::Bin2Dec(substr($info['mpeg']['video']['raw']['intra_quant'], 511, 1));
             $info['mpeg']['video']['raw']['intra_quant'] = Helper::Bin2Dec(substr($assortedinformation, 31, 1)) . substr(Helper::BigEndian2Bin(substr($MPEGstreamData, $VideoChunkOffset, 64)), 0, 511);
             if ($info['mpeg']['video']['raw']['non_intra_quant_flag']) {
                 $info['mpeg']['video']['raw']['non_intra_quant'] = substr($MPEGstreamData, $VideoChunkOffset, 64);
                 $VideoChunkOffset += 64;
             }
         } else {
             $info['mpeg']['video']['raw']['non_intra_quant_flag'] = (bool) Helper::Bin2Dec(substr($assortedinformation, 31, 1));
             if ($info['mpeg']['video']['raw']['non_intra_quant_flag']) {
                 $info['mpeg']['video']['raw']['non_intra_quant'] = substr($MPEGstreamData, $VideoChunkOffset, 64);
                 $VideoChunkOffset += 64;
             }
         }
         if ($info['mpeg']['video']['raw']['bitrate'] == 0x3ffff) {
             // 18 set bits
             $info['warning'][] = 'This version of GetId3Core() [' . $this->getid3->version() . '] cannot determine average bitrate of VBR MPEG video files';
             $info['mpeg']['video']['bitrate_mode'] = 'vbr';
         } else {
             $info['mpeg']['video']['bitrate'] = $info['mpeg']['video']['raw']['bitrate'] * 400;
             $info['mpeg']['video']['bitrate_mode'] = 'cbr';
             $info['video']['bitrate'] = $info['mpeg']['video']['bitrate'];
         }
         $info['video']['resolution_x'] = $info['mpeg']['video']['framesize_horizontal'];
         $info['video']['resolution_y'] = $info['mpeg']['video']['framesize_vertical'];
         $info['video']['frame_rate'] = $info['mpeg']['video']['frame_rate'];
         $info['video']['bitrate_mode'] = $info['mpeg']['video']['bitrate_mode'];
         $info['video']['pixel_aspect_ratio'] = $info['mpeg']['video']['pixel_aspect_ratio'];
         $info['video']['lossless'] = false;
         $info['video']['bits_per_sample'] = 24;
     } else {
         $info['error'][] = 'Could not find start of video block in the first 100,000 bytes (or before end of file) - this might not be an MPEG-video file?';
     }
     //0x000001B3 begins the sequence_header of every MPEG video stream.
     //But in MPEG-2, this header must immediately be followed by an
     //extension_start_code (0x000001B5) with a sequence_extension ID (1).
     //(This extension contains all the additional MPEG-2 stuff.)
     //MPEG-1 doesn't have this extension, so that's a sure way to tell the
     //difference between MPEG-1 and MPEG-2 video streams.
     if (substr($MPEGstreamData, $VideoChunkOffset, 4) == self::GETID3_MPEG_VIDEO_EXTENSION_START) {
         $info['video']['codec'] = 'MPEG-2';
     } else {
         $info['video']['codec'] = 'MPEG-1';
     }
     $AudioChunkOffset = 0;
     while (true) {
         while (substr($MPEGstreamData, $AudioChunkOffset++, 4) !== self::GETID3_MPEG_AUDIO_START) {
             if ($AudioChunkOffset >= $MPEGstreamDataLength) {
                 break 2;
             }
         }
         $getid3_temp = new GetId3Core();
         $getid3_temp->openfile($this->getid3->filename);
         $getid3_temp->info = $info;
         $getid3_mp3 = new Mp3($getid3_temp);
         for ($i = 0; $i <= 7; ++$i) {
             // some files have the MPEG-audio header 8 bytes after the end of the $00 $00 $01 $C0 signature, some have it up to 13 bytes (or more?) after
             // I have no idea why or what the difference is, so this is a stupid hack.
             // If anybody has any better idea of what's going on, please let me know - info@getid3.org
             fseek($getid3_temp->fp, ftell($this->getid3->fp), SEEK_SET);
             $getid3_temp->info = $info;
             // only overwrite real data if valid header found
             if ($getid3_mp3->decodeMPEGaudioHeader($AudioChunkOffset + 3 + 8 + $i, $getid3_temp->info, false)) {
                 $info = $getid3_temp->info;
                 $info['audio']['bitrate_mode'] = 'cbr';
                 $info['audio']['lossless'] = false;
                 unset($getid3_temp, $getid3_mp3);
                 break 2;
             }
         }
         unset($getid3_temp, $getid3_mp3);
     }
     // Temporary hack to account for interleaving overhead:
     if (!empty($info['video']['bitrate']) && !empty($info['audio']['bitrate'])) {
         $info['playtime_seconds'] = ($info['avdataend'] - $info['avdataoffset']) * 8 / ($info['video']['bitrate'] + $info['audio']['bitrate']);
         // Interleaved MPEG audio/video files have a certain amount of overhead that varies
         // by both video and audio bitrates, and not in any sensible, linear/logarithmic patter
         // Use interpolated lookup tables to approximately guess how much is overhead, because
         // playtime is calculated as filesize / total-bitrate
         $info['playtime_seconds'] *= $this->MPEGsystemNonOverheadPercentage($info['video']['bitrate'], $info['audio']['bitrate']);
         //switch ($info['video']['bitrate']) {
         //	case('5000000'):
         //		$multiplier = 0.93292642112380355828048824319889;
         //		break;
         //	case('5500000'):
         //		$multiplier = 0.93582895375200989965359777343219;
         //		break;
         //	case('6000000'):
         //		$multiplier = 0.93796247714820932532911373859139;
         //		break;
         //	case('7000000'):
         //		$multiplier = 0.9413264083635103463010117778776;
         //		break;
         //	default:
         //		$multiplier = 1;
         //		break;
         //}
         //$info['playtime_seconds'] *= $multiplier;
         //$info['warning'][] = 'Interleaved MPEG audio/video playtime may be inaccurate. With current hack should be within a few seconds of accurate. Report to info@getid3.org if off by more than 10 seconds.';
         if ($info['video']['bitrate'] < 50000) {
             $info['warning'][] = 'Interleaved MPEG audio/video playtime may be slightly inaccurate for video bitrates below 100kbps. Except in extreme low-bitrate situations, error should be less than 1%. Report to info@getid3.org if greater than this.';
         }
     }
     return true;
 }
Пример #21
0
 /**
  * @param type $BonkTagName
  */
 public function HandleBonkTags($BonkTagName)
 {
     $info =& $this->getid3->info;
     switch ($BonkTagName) {
         case 'BONK':
             // shortcut
             $thisfile_bonk_BONK =& $info['bonk']['BONK'];
             $BonkData = "" . 'BONK' . fread($this->getid3->fp, 17);
             $thisfile_bonk_BONK['version'] = Helper::LittleEndian2Int(substr($BonkData, 5, 1));
             $thisfile_bonk_BONK['number_samples'] = Helper::LittleEndian2Int(substr($BonkData, 6, 4));
             $thisfile_bonk_BONK['sample_rate'] = Helper::LittleEndian2Int(substr($BonkData, 10, 4));
             $thisfile_bonk_BONK['channels'] = Helper::LittleEndian2Int(substr($BonkData, 14, 1));
             $thisfile_bonk_BONK['lossless'] = (bool) Helper::LittleEndian2Int(substr($BonkData, 15, 1));
             $thisfile_bonk_BONK['joint_stereo'] = (bool) Helper::LittleEndian2Int(substr($BonkData, 16, 1));
             $thisfile_bonk_BONK['number_taps'] = Helper::LittleEndian2Int(substr($BonkData, 17, 2));
             $thisfile_bonk_BONK['downsampling_ratio'] = Helper::LittleEndian2Int(substr($BonkData, 19, 1));
             $thisfile_bonk_BONK['samples_per_packet'] = Helper::LittleEndian2Int(substr($BonkData, 20, 2));
             $info['avdataoffset'] = $thisfile_bonk_BONK['offset'] + 5 + 17;
             $info['avdataend'] = $thisfile_bonk_BONK['offset'] + $thisfile_bonk_BONK['size'];
             $info['fileformat'] = 'bonk';
             $info['audio']['dataformat'] = 'bonk';
             $info['audio']['bitrate_mode'] = 'vbr';
             // assumed
             $info['audio']['channels'] = $thisfile_bonk_BONK['channels'];
             $info['audio']['sample_rate'] = $thisfile_bonk_BONK['sample_rate'];
             $info['audio']['channelmode'] = $thisfile_bonk_BONK['joint_stereo'] ? 'joint stereo' : 'stereo';
             $info['audio']['lossless'] = $thisfile_bonk_BONK['lossless'];
             $info['audio']['codec'] = 'bonk';
             $info['playtime_seconds'] = $thisfile_bonk_BONK['number_samples'] / ($thisfile_bonk_BONK['sample_rate'] * $thisfile_bonk_BONK['channels']);
             if ($info['playtime_seconds'] > 0) {
                 $info['audio']['bitrate'] = ($info['bonk']['dataend'] - $info['bonk']['dataoffset']) * 8 / $info['playtime_seconds'];
             }
             break;
         case 'INFO':
             // shortcut
             $thisfile_bonk_INFO =& $info['bonk']['INFO'];
             $thisfile_bonk_INFO['version'] = Helper::LittleEndian2Int(fread($this->getid3->fp, 1));
             $thisfile_bonk_INFO['entries_count'] = 0;
             $NextInfoDataPair = fread($this->getid3->fp, 5);
             if (!$this->BonkIsValidTagName(substr($NextInfoDataPair, 1, 4))) {
                 while (!feof($this->getid3->fp)) {
                     //$CurrentSeekInfo['offset']  = GetId3_lib::LittleEndian2Int(substr($NextInfoDataPair, 0, 4));
                     //$CurrentSeekInfo['nextbit'] = GetId3_lib::LittleEndian2Int(substr($NextInfoDataPair, 4, 1));
                     //$thisfile_bonk_INFO[] = $CurrentSeekInfo;
                     $NextInfoDataPair = fread($this->getid3->fp, 5);
                     if ($this->BonkIsValidTagName(substr($NextInfoDataPair, 1, 4))) {
                         fseek($this->getid3->fp, -5, SEEK_CUR);
                         break;
                     }
                     ++$thisfile_bonk_INFO['entries_count'];
                 }
             }
             break;
         case 'META':
             $BonkData = "" . 'META' . fread($this->getid3->fp, $info['bonk']['META']['size'] - 5);
             $info['bonk']['META']['version'] = Helper::LittleEndian2Int(substr($BonkData, 5, 1));
             $MetaTagEntries = floor((strlen($BonkData) - 8 - 6) / 8);
             // BonkData - xxxxmeta - ØMETA
             $offset = 6;
             for ($i = 0; $i < $MetaTagEntries; ++$i) {
                 $MetaEntryTagName = substr($BonkData, $offset, 4);
                 $offset += 4;
                 $MetaEntryTagOffset = Helper::LittleEndian2Int(substr($BonkData, $offset, 4));
                 $offset += 4;
                 $info['bonk']['META']['tags'][$MetaEntryTagName] = $MetaEntryTagOffset;
             }
             break;
         case ' ID3':
             $info['audio']['encoder'] = 'Extended BONK v0.9+';
             // ID3v2 checking is optional
             if (class_exists('Helpers\\GetId3\\Module\\Tag\\Id3v2')) {
                 $getid3_temp = new GetId3Core();
                 $getid3_temp->openfile($this->getid3->filename);
                 $getid3_id3v2 = new Id3v2($getid3_temp);
                 $getid3_id3v2->StartingOffset = $info['bonk'][' ID3']['offset'] + 2;
                 $info['bonk'][' ID3']['valid'] = $getid3_id3v2->analyze();
                 if ($info['bonk'][' ID3']['valid']) {
                     $info['id3v2'] = $getid3_temp->info['id3v2'];
                 }
                 unset($getid3_temp, $getid3_id3v2);
             }
             break;
         default:
             $info['warning'][] = 'Unexpected Bonk tag "' . $BonkTagName . '" at offset ' . $info['bonk'][$BonkTagName]['offset'];
             break;
     }
 }
Пример #22
0
 /**
  * @return bool
  */
 public function analyze()
 {
     $info =& $this->getid3->info;
     $info['fileformat'] = 'gzip';
     $start_length = 10;
     $unpack_header = 'a1id1/a1id2/a1cmethod/a1flags/a4mtime/a1xflags/a1os';
     //+---+---+---+---+---+---+---+---+---+---+
     //|ID1|ID2|CM |FLG|     MTIME     |XFL|OS |
     //+---+---+---+---+---+---+---+---+---+---+
     if ($info['filesize'] > $info['php_memory_limit']) {
         $info['error'][] = 'File is too large (' . number_format($info['filesize']) . ' bytes) to read into memory (limit: ' . number_format($info['php_memory_limit'] / 1048576) . 'MB)';
         return false;
     }
     fseek($this->getid3->fp, 0);
     $buffer = fread($this->getid3->fp, $info['filesize']);
     $arr_members = explode("‹", $buffer);
     while (true) {
         $is_wrong_members = false;
         $num_members = intval(count($arr_members));
         for ($i = 0; $i < $num_members; ++$i) {
             if (strlen($arr_members[$i]) == 0) {
                 continue;
             }
             $buf = "‹" . $arr_members[$i];
             $attr = unpack($unpack_header, substr($buf, 0, $start_length));
             if (!$this->get_os_type(ord($attr['os']))) {
                 // Merge member with previous if wrong OS type
                 $arr_members[$i - 1] .= $buf;
                 $arr_members[$i] = '';
                 $is_wrong_members = true;
                 continue;
             }
         }
         if (!$is_wrong_members) {
             break;
         }
     }
     $info['gzip']['files'] = array();
     $fpointer = 0;
     $idx = 0;
     for ($i = 0; $i < $num_members; ++$i) {
         if (strlen($arr_members[$i]) == 0) {
             continue;
         }
         $thisInfo =& $info['gzip']['member_header'][++$idx];
         $buff = "‹" . $arr_members[$i];
         $attr = unpack($unpack_header, substr($buff, 0, $start_length));
         $thisInfo['filemtime'] = Helper::LittleEndian2Int($attr['mtime']);
         $thisInfo['raw']['id1'] = ord($attr['cmethod']);
         $thisInfo['raw']['id2'] = ord($attr['cmethod']);
         $thisInfo['raw']['cmethod'] = ord($attr['cmethod']);
         $thisInfo['raw']['os'] = ord($attr['os']);
         $thisInfo['raw']['xflags'] = ord($attr['xflags']);
         $thisInfo['raw']['flags'] = ord($attr['flags']);
         $thisInfo['flags']['crc16'] = (bool) ($thisInfo['raw']['flags'] & 0x2);
         $thisInfo['flags']['extra'] = (bool) ($thisInfo['raw']['flags'] & 0x4);
         $thisInfo['flags']['filename'] = (bool) ($thisInfo['raw']['flags'] & 0x8);
         $thisInfo['flags']['comment'] = (bool) ($thisInfo['raw']['flags'] & 0x10);
         $thisInfo['compression'] = $this->get_xflag_type($thisInfo['raw']['xflags']);
         $thisInfo['os'] = $this->get_os_type($thisInfo['raw']['os']);
         if (!$thisInfo['os']) {
             $info['error'][] = 'Read error on gzip file';
             return false;
         }
         $fpointer = 10;
         $arr_xsubfield = array();
         // bit 2 - FLG.FEXTRA
         //+---+---+=================================+
         //| XLEN  |...XLEN bytes of "extra field"...|
         //+---+---+=================================+
         if ($thisInfo['flags']['extra']) {
             $w_xlen = substr($buff, $fpointer, 2);
             $xlen = Helper::LittleEndian2Int($w_xlen);
             $fpointer += 2;
             $thisInfo['raw']['xfield'] = substr($buff, $fpointer, $xlen);
             // Extra SubFields
             //+---+---+---+---+==================================+
             //|SI1|SI2|  LEN  |... LEN bytes of subfield data ...|
             //+---+---+---+---+==================================+
             $idx = 0;
             while (true) {
                 if ($idx >= $xlen) {
                     break;
                 }
                 $si1 = ord(substr($buff, $fpointer + $idx++, 1));
                 $si2 = ord(substr($buff, $fpointer + $idx++, 1));
                 if ($si1 == 0x41 && $si2 == 0x70) {
                     $w_xsublen = substr($buff, $fpointer + $idx, 2);
                     $xsublen = Helper::LittleEndian2Int($w_xsublen);
                     $idx += 2;
                     $arr_xsubfield[] = substr($buff, $fpointer + $idx, $xsublen);
                     $idx += $xsublen;
                 } else {
                     break;
                 }
             }
             $fpointer += $xlen;
         }
         // bit 3 - FLG.FNAME
         //+=========================================+
         //|...original file name, zero-terminated...|
         //+=========================================+
         // GZIP files may have only one file, with no filename, so assume original filename is current filename without .gz
         $thisInfo['filename'] = preg_replace('#\\.gz$#i', '', $info['filename']);
         if ($thisInfo['flags']['filename']) {
             while (true) {
                 if (ord($buff[$fpointer]) == 0) {
                     ++$fpointer;
                     break;
                 }
                 $thisInfo['filename'] .= $buff[$fpointer];
                 ++$fpointer;
             }
         }
         // bit 4 - FLG.FCOMMENT
         //+===================================+
         //|...file comment, zero-terminated...|
         //+===================================+
         if ($thisInfo['flags']['comment']) {
             while (true) {
                 if (ord($buff[$fpointer]) == 0) {
                     ++$fpointer;
                     break;
                 }
                 $thisInfo['comment'] .= $buff[$fpointer];
                 ++$fpointer;
             }
         }
         // bit 1 - FLG.FHCRC
         //+---+---+
         //| CRC16 |
         //+---+---+
         if ($thisInfo['flags']['crc16']) {
             $w_crc = substr($buff, $fpointer, 2);
             $thisInfo['crc16'] = Helper::LittleEndian2Int($w_crc);
             $fpointer += 2;
         }
         // bit 0 - FLG.FTEXT
         //if ($thisInfo['raw']['flags'] & 0x01) {
         //	Ignored...
         //}
         // bits 5, 6, 7 - reserved
         $thisInfo['crc32'] = Helper::LittleEndian2Int(substr($buff, strlen($buff) - 8, 4));
         $thisInfo['filesize'] = Helper::LittleEndian2Int(substr($buff, strlen($buff) - 4));
         $info['gzip']['files'] = Helper::array_merge_clobber($info['gzip']['files'], Helper::CreateDeepArray($thisInfo['filename'], '/', $thisInfo['filesize']));
         if ($this->option_gzip_parse_contents) {
             // Try to inflate GZip
             $csize = 0;
             $inflated = '';
             $chkcrc32 = '';
             if (function_exists('gzinflate')) {
                 $cdata = substr($buff, $fpointer);
                 $cdata = substr($cdata, 0, strlen($cdata) - 8);
                 $csize = strlen($cdata);
                 $inflated = gzinflate($cdata);
                 // Calculate CRC32 for inflated content
                 $thisInfo['crc32_valid'] = (bool) (sprintf('%u', crc32($inflated)) == $thisInfo['crc32']);
                 // determine format
                 $formattest = substr($inflated, 0, 32774);
                 $getid3_temp = new GetId3Core();
                 $determined_format = $getid3_temp->GetFileFormat($formattest);
                 unset($getid3_temp);
                 // file format is determined
                 $determined_format['module'] = isset($determined_format['module']) ? $determined_format['module'] : '';
                 switch ($determined_format['module']) {
                     case 'tar':
                         // view TAR-file info
                         if (class_exists($determined_format['class'])) {
                             if (($temp_tar_filename = tempnam(GetId3Core::getTempDir(), 'getID3')) === false) {
                                 // can't find anywhere to create a temp file, abort
                                 $info['error'][] = 'Unable to create temp file to parse TAR inside GZIP file';
                                 break;
                             }
                             if ($fp_temp_tar = fopen($temp_tar_filename, 'w+b')) {
                                 fwrite($fp_temp_tar, $inflated);
                                 fclose($fp_temp_tar);
                                 $getid3_temp = new GetId3Core();
                                 $getid3_temp->openfile($temp_tar_filename);
                                 $getid3_tar = new Tar($getid3_temp);
                                 $getid3_tar->analyze();
                                 $info['gzip']['member_header'][$idx]['tar'] = $getid3_temp->info['tar'];
                                 unset($getid3_temp, $getid3_tar);
                                 unlink($temp_tar_filename);
                             } else {
                                 $info['error'][] = 'Unable to fopen() temp file to parse TAR inside GZIP file';
                                 break;
                             }
                         }
                         break;
                     case '':
                     default:
                         // unknown or unhandled format
                         break;
                 }
             }
         }
     }
     return true;
 }
Пример #23
0
 /**
  * @return bool
  */
 public function analyze()
 {
     $info =& $this->getid3->info;
     fseek($this->getid3->fp, $info['avdataoffset'], SEEK_SET);
     while (true) {
         $wavpackheader = fread($this->getid3->fp, 32);
         if (ftell($this->getid3->fp) >= $info['avdataend']) {
             break;
         } elseif (feof($this->getid3->fp)) {
             break;
         } elseif (isset($info['wavpack']['blockheader']['total_samples']) && isset($info['wavpack']['blockheader']['block_samples']) && $info['wavpack']['blockheader']['total_samples'] > 0 && $info['wavpack']['blockheader']['block_samples'] > 0 && (!isset($info['wavpack']['riff_trailer_size']) || $info['wavpack']['riff_trailer_size'] <= 0) && (isset($info['wavpack']['config_flags']['md5_checksum']) && $info['wavpack']['config_flags']['md5_checksum'] === false || !empty($info['md5_data_source']))) {
             break;
         }
         $blockheader_offset = ftell($this->getid3->fp) - 32;
         $blockheader_magic = substr($wavpackheader, 0, 4);
         $blockheader_size = Helper::LittleEndian2Int(substr($wavpackheader, 4, 4));
         $magic = 'wvpk';
         if ($blockheader_magic != $magic) {
             $info['error'][] = 'Expecting "' . Helper::PrintHexBytes($magic) . '" at offset ' . $blockheader_offset . ', found "' . Helper::PrintHexBytes($blockheader_magic) . '"';
             switch (isset($info['audio']['dataformat']) ? $info['audio']['dataformat'] : '') {
                 case 'wavpack':
                 case 'wvc':
                     break;
                 default:
                     unset($info['fileformat']);
                     unset($info['audio']);
                     unset($info['wavpack']);
                     break;
             }
             return false;
         }
         if (empty($info['wavpack']['blockheader']['block_samples']) || empty($info['wavpack']['blockheader']['total_samples']) || $info['wavpack']['blockheader']['block_samples'] <= 0 || $info['wavpack']['blockheader']['total_samples'] <= 0) {
             // Also, it is possible that the first block might not have
             // any samples (block_samples == 0) and in this case you should skip blocks
             // until you find one with samples because the other information (like
             // total_samples) are not guaranteed to be correct until (block_samples > 0)
             // Finally, I have defined a format for files in which the length is not known
             // (for example when raw files are created using pipes). In these cases
             // total_samples will be -1 and you must seek to the final block to determine
             // the total number of samples.
             $info['audio']['dataformat'] = 'wavpack';
             $info['fileformat'] = 'wavpack';
             $info['audio']['lossless'] = true;
             $info['audio']['bitrate_mode'] = 'vbr';
             $info['wavpack']['blockheader']['offset'] = $blockheader_offset;
             $info['wavpack']['blockheader']['magic'] = $blockheader_magic;
             $info['wavpack']['blockheader']['size'] = $blockheader_size;
             if ($info['wavpack']['blockheader']['size'] >= 0x100000) {
                 $info['error'][] = 'Expecting WavPack block size less than "0x100000", found "' . $info['wavpack']['blockheader']['size'] . '" at offset ' . $info['wavpack']['blockheader']['offset'];
                 switch (isset($info['audio']['dataformat']) ? $info['audio']['dataformat'] : '') {
                     case 'wavpack':
                     case 'wvc':
                         break;
                     default:
                         unset($info['fileformat']);
                         unset($info['audio']);
                         unset($info['wavpack']);
                         break;
                 }
                 return false;
             }
             $info['wavpack']['blockheader']['minor_version'] = ord($wavpackheader[8]);
             $info['wavpack']['blockheader']['major_version'] = ord($wavpackheader[9]);
             if ($info['wavpack']['blockheader']['major_version'] != 4 || $info['wavpack']['blockheader']['minor_version'] < 4 && $info['wavpack']['blockheader']['minor_version'] > 16) {
                 $info['error'][] = 'Expecting WavPack version between "4.2" and "4.16", found version "' . $info['wavpack']['blockheader']['major_version'] . '.' . $info['wavpack']['blockheader']['minor_version'] . '" at offset ' . $info['wavpack']['blockheader']['offset'];
                 switch (isset($info['audio']['dataformat']) ? $info['audio']['dataformat'] : '') {
                     case 'wavpack':
                     case 'wvc':
                         break;
                     default:
                         unset($info['fileformat']);
                         unset($info['audio']);
                         unset($info['wavpack']);
                         break;
                 }
                 return false;
             }
             $info['wavpack']['blockheader']['track_number'] = ord($wavpackheader[10]);
             // unused
             $info['wavpack']['blockheader']['index_number'] = ord($wavpackheader[11]);
             // unused
             $info['wavpack']['blockheader']['total_samples'] = Helper::LittleEndian2Int(substr($wavpackheader, 12, 4));
             $info['wavpack']['blockheader']['block_index'] = Helper::LittleEndian2Int(substr($wavpackheader, 16, 4));
             $info['wavpack']['blockheader']['block_samples'] = Helper::LittleEndian2Int(substr($wavpackheader, 20, 4));
             $info['wavpack']['blockheader']['flags_raw'] = Helper::LittleEndian2Int(substr($wavpackheader, 24, 4));
             $info['wavpack']['blockheader']['crc'] = Helper::LittleEndian2Int(substr($wavpackheader, 28, 4));
             $info['wavpack']['blockheader']['flags']['bytes_per_sample'] = 1 + ($info['wavpack']['blockheader']['flags_raw'] & 0x3);
             $info['wavpack']['blockheader']['flags']['mono'] = (bool) ($info['wavpack']['blockheader']['flags_raw'] & 0x4);
             $info['wavpack']['blockheader']['flags']['hybrid'] = (bool) ($info['wavpack']['blockheader']['flags_raw'] & 0x8);
             $info['wavpack']['blockheader']['flags']['joint_stereo'] = (bool) ($info['wavpack']['blockheader']['flags_raw'] & 0x10);
             $info['wavpack']['blockheader']['flags']['cross_decorrelation'] = (bool) ($info['wavpack']['blockheader']['flags_raw'] & 0x20);
             $info['wavpack']['blockheader']['flags']['hybrid_noiseshape'] = (bool) ($info['wavpack']['blockheader']['flags_raw'] & 0x40);
             $info['wavpack']['blockheader']['flags']['ieee_32bit_float'] = (bool) ($info['wavpack']['blockheader']['flags_raw'] & 0x80);
             $info['wavpack']['blockheader']['flags']['int_32bit'] = (bool) ($info['wavpack']['blockheader']['flags_raw'] & 0x100);
             $info['wavpack']['blockheader']['flags']['hybrid_bitrate_noise'] = (bool) ($info['wavpack']['blockheader']['flags_raw'] & 0x200);
             $info['wavpack']['blockheader']['flags']['hybrid_balance_noise'] = (bool) ($info['wavpack']['blockheader']['flags_raw'] & 0x400);
             $info['wavpack']['blockheader']['flags']['multichannel_initial'] = (bool) ($info['wavpack']['blockheader']['flags_raw'] & 0x800);
             $info['wavpack']['blockheader']['flags']['multichannel_final'] = (bool) ($info['wavpack']['blockheader']['flags_raw'] & 0x1000);
             $info['audio']['lossless'] = !$info['wavpack']['blockheader']['flags']['hybrid'];
         }
         while (!feof($this->getid3->fp) && ftell($this->getid3->fp) < $blockheader_offset + $blockheader_size + 8) {
             $metablock = array('offset' => ftell($this->getid3->fp));
             $metablockheader = fread($this->getid3->fp, 2);
             if (feof($this->getid3->fp)) {
                 break;
             }
             $metablock['id'] = ord($metablockheader[0]);
             $metablock['function_id'] = $metablock['id'] & 0x3f;
             $metablock['function_name'] = $this->WavPackMetablockNameLookup($metablock['function_id']);
             // The 0x20 bit in the id of the meta subblocks (which is defined as
             // ID_OPTIONAL_DATA) is a permanent part of the id. The idea is that
             // if a decoder encounters an id that it does not know about, it uses
             // that "ID_OPTIONAL_DATA" flag to determine what to do. If it is set
             // then the decoder simply ignores the metadata, but if it is zero
             // then the decoder should quit because it means that an understanding
             // of the metadata is required to correctly decode the audio.
             $metablock['non_decoder'] = (bool) ($metablock['id'] & 0x20);
             $metablock['padded_data'] = (bool) ($metablock['id'] & 0x40);
             $metablock['large_block'] = (bool) ($metablock['id'] & 0x80);
             if ($metablock['large_block']) {
                 $metablockheader .= fread($this->getid3->fp, 2);
             }
             $metablock['size'] = Helper::LittleEndian2Int(substr($metablockheader, 1)) * 2;
             // size is stored in words
             $metablock['data'] = null;
             if ($metablock['size'] > 0) {
                 switch ($metablock['function_id']) {
                     case 0x21:
                         // ID_RIFF_HEADER
                     // ID_RIFF_HEADER
                     case 0x22:
                         // ID_RIFF_TRAILER
                     // ID_RIFF_TRAILER
                     case 0x23:
                         // ID_REPLAY_GAIN
                     // ID_REPLAY_GAIN
                     case 0x24:
                         // ID_CUESHEET
                     // ID_CUESHEET
                     case 0x25:
                         // ID_CONFIG_BLOCK
                     // ID_CONFIG_BLOCK
                     case 0x26:
                         // ID_MD5_CHECKSUM
                         $metablock['data'] = fread($this->getid3->fp, $metablock['size']);
                         if ($metablock['padded_data']) {
                             // padded to the nearest even byte
                             --$metablock['size'];
                             $metablock['data'] = substr($metablock['data'], 0, -1);
                         }
                         break;
                     case 0x0:
                         // ID_DUMMY
                     // ID_DUMMY
                     case 0x1:
                         // ID_ENCODER_INFO
                     // ID_ENCODER_INFO
                     case 0x2:
                         // ID_DECORR_TERMS
                     // ID_DECORR_TERMS
                     case 0x3:
                         // ID_DECORR_WEIGHTS
                     // ID_DECORR_WEIGHTS
                     case 0x4:
                         // ID_DECORR_SAMPLES
                     // ID_DECORR_SAMPLES
                     case 0x5:
                         // ID_ENTROPY_VARS
                     // ID_ENTROPY_VARS
                     case 0x6:
                         // ID_HYBRID_PROFILE
                     // ID_HYBRID_PROFILE
                     case 0x7:
                         // ID_SHAPING_WEIGHTS
                     // ID_SHAPING_WEIGHTS
                     case 0x8:
                         // ID_FLOAT_INFO
                     // ID_FLOAT_INFO
                     case 0x9:
                         // ID_INT32_INFO
                     // ID_INT32_INFO
                     case 0xa:
                         // ID_WV_BITSTREAM
                     // ID_WV_BITSTREAM
                     case 0xb:
                         // ID_WVC_BITSTREAM
                     // ID_WVC_BITSTREAM
                     case 0xc:
                         // ID_WVX_BITSTREAM
                     // ID_WVX_BITSTREAM
                     case 0xd:
                         // ID_CHANNEL_INFO
                         fseek($this->getid3->fp, $metablock['offset'] + ($metablock['large_block'] ? 4 : 2) + $metablock['size'], SEEK_SET);
                         break;
                     default:
                         $info['warning'][] = 'Unexpected metablock type "0x' . str_pad(dechex($metablock['function_id']), 2, '0', STR_PAD_LEFT) . '" at offset ' . $metablock['offset'];
                         fseek($this->getid3->fp, $metablock['offset'] + ($metablock['large_block'] ? 4 : 2) + $metablock['size'], SEEK_SET);
                         break;
                 }
                 switch ($metablock['function_id']) {
                     case 0x21:
                         // ID_RIFF_HEADER
                         $original_wav_filesize = Helper::LittleEndian2Int(substr($metablock['data'], 4, 4));
                         $getid3_temp = new GetId3Core();
                         $getid3_temp->openfile($this->getid3->filename);
                         $getid3_riff = new Riff($getid3_temp);
                         $getid3_riff->ParseRIFFdata($metablock['data']);
                         $metablock['riff'] = $getid3_temp->info['riff'];
                         $info['audio']['sample_rate'] = $getid3_temp->info['riff']['raw']['fmt ']['nSamplesPerSec'];
                         unset($getid3_riff, $getid3_temp);
                         $metablock['riff']['original_filesize'] = $original_wav_filesize;
                         $info['wavpack']['riff_trailer_size'] = $original_wav_filesize - $metablock['riff']['WAVE']['data'][0]['size'] - $metablock['riff']['header_size'];
                         $info['playtime_seconds'] = $info['wavpack']['blockheader']['total_samples'] / $info['audio']['sample_rate'];
                         // Safe RIFF header in case there's a RIFF footer later
                         $metablockRIFFheader = $metablock['data'];
                         break;
                     case 0x22:
                         // ID_RIFF_TRAILER
                         $metablockRIFFfooter = $metablockRIFFheader . $metablock['data'];
                         $startoffset = $metablock['offset'] + ($metablock['large_block'] ? 4 : 2);
                         $getid3_temp = new GetId3Core();
                         $getid3_temp->openfile($this->getid3->filename);
                         $getid3_temp->info['avdataend'] = $info['avdataend'];
                         $getid3_temp->info['fileformat'] = 'riff';
                         $getid3_riff = new Riff($getid3_temp);
                         $metablock['riff'] = $getid3_riff->ParseRIFF($startoffset, $startoffset + $metablock['size']);
                         if (!empty($metablock['riff']['INFO'])) {
                             $getid3_riff->RIFFcommentsParse($metablock['riff']['INFO'], $metablock['comments']);
                             $info['tags']['riff'] = $metablock['comments'];
                         }
                         unset($getid3_temp, $getid3_riff);
                         break;
                     case 0x23:
                         // ID_REPLAY_GAIN
                         $info['warning'][] = 'WavPack "Replay Gain" contents not yet handled by GetId3Core() in metablock at offset ' . $metablock['offset'];
                         break;
                     case 0x24:
                         // ID_CUESHEET
                         $info['warning'][] = 'WavPack "Cuesheet" contents not yet handled by GetId3Core() in metablock at offset ' . $metablock['offset'];
                         break;
                     case 0x25:
                         // ID_CONFIG_BLOCK
                         $metablock['flags_raw'] = Helper::LittleEndian2Int(substr($metablock['data'], 0, 3));
                         $metablock['flags']['adobe_mode'] = (bool) ($metablock['flags_raw'] & 0x1);
                         // "adobe" mode for 32-bit floats
                         $metablock['flags']['fast_flag'] = (bool) ($metablock['flags_raw'] & 0x2);
                         // fast mode
                         $metablock['flags']['very_fast_flag'] = (bool) ($metablock['flags_raw'] & 0x4);
                         // double fast
                         $metablock['flags']['high_flag'] = (bool) ($metablock['flags_raw'] & 0x8);
                         // high quality mode
                         $metablock['flags']['very_high_flag'] = (bool) ($metablock['flags_raw'] & 0x10);
                         // double high (not used yet)
                         $metablock['flags']['bitrate_kbps'] = (bool) ($metablock['flags_raw'] & 0x20);
                         // bitrate is kbps, not bits / sample
                         $metablock['flags']['auto_shaping'] = (bool) ($metablock['flags_raw'] & 0x40);
                         // automatic noise shaping
                         $metablock['flags']['shape_override'] = (bool) ($metablock['flags_raw'] & 0x80);
                         // shaping mode specified
                         $metablock['flags']['joint_override'] = (bool) ($metablock['flags_raw'] & 0x100);
                         // joint-stereo mode specified
                         $metablock['flags']['copy_time'] = (bool) ($metablock['flags_raw'] & 0x200);
                         // copy file-time from source
                         $metablock['flags']['create_exe'] = (bool) ($metablock['flags_raw'] & 0x400);
                         // create executable
                         $metablock['flags']['create_wvc'] = (bool) ($metablock['flags_raw'] & 0x800);
                         // create correction file
                         $metablock['flags']['optimize_wvc'] = (bool) ($metablock['flags_raw'] & 0x1000);
                         // maximize bybrid compression
                         $metablock['flags']['quality_mode'] = (bool) ($metablock['flags_raw'] & 0x2000);
                         // psychoacoustic quality mode
                         $metablock['flags']['raw_flag'] = (bool) ($metablock['flags_raw'] & 0x4000);
                         // raw mode (not implemented yet)
                         $metablock['flags']['calc_noise'] = (bool) ($metablock['flags_raw'] & 0x8000);
                         // calc noise in hybrid mode
                         $metablock['flags']['lossy_mode'] = (bool) ($metablock['flags_raw'] & 0x10000);
                         // obsolete (for information)
                         $metablock['flags']['extra_mode'] = (bool) ($metablock['flags_raw'] & 0x20000);
                         // extra processing mode
                         $metablock['flags']['skip_wvx'] = (bool) ($metablock['flags_raw'] & 0x40000);
                         // no wvx stream w/ floats & big ints
                         $metablock['flags']['md5_checksum'] = (bool) ($metablock['flags_raw'] & 0x80000);
                         // compute & store MD5 signature
                         $metablock['flags']['quiet_mode'] = (bool) ($metablock['flags_raw'] & 0x100000);
                         // don't report progress %
                         $info['wavpack']['config_flags'] = $metablock['flags'];
                         $info['audio']['encoder_options'] = '';
                         if ($info['wavpack']['blockheader']['flags']['hybrid']) {
                             $info['audio']['encoder_options'] .= ' -b???';
                         }
                         $info['audio']['encoder_options'] .= $metablock['flags']['adobe_mode'] ? ' -a' : '';
                         $info['audio']['encoder_options'] .= $metablock['flags']['optimize_wvc'] ? ' -cc' : '';
                         $info['audio']['encoder_options'] .= $metablock['flags']['create_exe'] ? ' -e' : '';
                         $info['audio']['encoder_options'] .= $metablock['flags']['fast_flag'] ? ' -f' : '';
                         $info['audio']['encoder_options'] .= $metablock['flags']['joint_override'] ? ' -j?' : '';
                         $info['audio']['encoder_options'] .= $metablock['flags']['high_flag'] ? ' -h' : '';
                         $info['audio']['encoder_options'] .= $metablock['flags']['md5_checksum'] ? ' -m' : '';
                         $info['audio']['encoder_options'] .= $metablock['flags']['calc_noise'] ? ' -n' : '';
                         $info['audio']['encoder_options'] .= $metablock['flags']['shape_override'] ? ' -s?' : '';
                         $info['audio']['encoder_options'] .= $metablock['flags']['extra_mode'] ? ' -x?' : '';
                         if (!empty($info['audio']['encoder_options'])) {
                             $info['audio']['encoder_options'] = trim($info['audio']['encoder_options']);
                         } elseif (isset($info['audio']['encoder_options'])) {
                             unset($info['audio']['encoder_options']);
                         }
                         break;
                     case 0x26:
                         // ID_MD5_CHECKSUM
                         if (strlen($metablock['data']) == 16) {
                             $info['md5_data_source'] = strtolower(Helper::PrintHexBytes($metablock['data'], true, false, false));
                         } else {
                             $info['warning'][] = 'Expecting 16 bytes of WavPack "MD5 Checksum" in metablock at offset ' . $metablock['offset'] . ', but found ' . strlen($metablock['data']) . ' bytes';
                         }
                         break;
                     case 0x0:
                         // ID_DUMMY
                     // ID_DUMMY
                     case 0x1:
                         // ID_ENCODER_INFO
                     // ID_ENCODER_INFO
                     case 0x2:
                         // ID_DECORR_TERMS
                     // ID_DECORR_TERMS
                     case 0x3:
                         // ID_DECORR_WEIGHTS
                     // ID_DECORR_WEIGHTS
                     case 0x4:
                         // ID_DECORR_SAMPLES
                     // ID_DECORR_SAMPLES
                     case 0x5:
                         // ID_ENTROPY_VARS
                     // ID_ENTROPY_VARS
                     case 0x6:
                         // ID_HYBRID_PROFILE
                     // ID_HYBRID_PROFILE
                     case 0x7:
                         // ID_SHAPING_WEIGHTS
                     // ID_SHAPING_WEIGHTS
                     case 0x8:
                         // ID_FLOAT_INFO
                     // ID_FLOAT_INFO
                     case 0x9:
                         // ID_INT32_INFO
                     // ID_INT32_INFO
                     case 0xa:
                         // ID_WV_BITSTREAM
                     // ID_WV_BITSTREAM
                     case 0xb:
                         // ID_WVC_BITSTREAM
                     // ID_WVC_BITSTREAM
                     case 0xc:
                         // ID_WVX_BITSTREAM
                     // ID_WVX_BITSTREAM
                     case 0xd:
                         // ID_CHANNEL_INFO
                         unset($metablock);
                         break;
                 }
             }
             if (!empty($metablock)) {
                 $info['wavpack']['metablocks'][] = $metablock;
             }
         }
     }
     $info['audio']['encoder'] = 'WavPack v' . $info['wavpack']['blockheader']['major_version'] . '.' . str_pad($info['wavpack']['blockheader']['minor_version'], 2, '0', STR_PAD_LEFT);
     $info['audio']['bits_per_sample'] = $info['wavpack']['blockheader']['flags']['bytes_per_sample'] * 8;
     $info['audio']['channels'] = $info['wavpack']['blockheader']['flags']['mono'] ? 1 : 2;
     if (!empty($info['playtime_seconds'])) {
         $info['audio']['bitrate'] = ($info['avdataend'] - $info['avdataoffset']) * 8 / $info['playtime_seconds'];
     } else {
         $info['audio']['dataformat'] = 'wvc';
     }
     return true;
 }
Пример #24
0
 /**
  * @staticvar type $shorten_present
  *
  * @return bool
  */
 public function analyze()
 {
     $info =& $this->getid3->info;
     fseek($this->getid3->fp, $info['avdataoffset'], SEEK_SET);
     $ShortenHeader = fread($this->getid3->fp, 8);
     $magic = 'ajkg';
     if (substr($ShortenHeader, 0, 4) != $magic) {
         $info['error'][] = 'Expecting "' . Helper::PrintHexBytes($magic) . '" at offset ' . $info['avdataoffset'] . ', found "' . Helper::PrintHexBytes(substr($ShortenHeader, 0, 4)) . '"';
         return false;
     }
     $info['fileformat'] = 'shn';
     $info['audio']['dataformat'] = 'shn';
     $info['audio']['lossless'] = true;
     $info['audio']['bitrate_mode'] = 'vbr';
     $info['shn']['version'] = Helper::LittleEndian2Int(substr($ShortenHeader, 4, 1));
     fseek($this->getid3->fp, $info['avdataend'] - 12, SEEK_SET);
     $SeekTableSignatureTest = fread($this->getid3->fp, 12);
     $info['shn']['seektable']['present'] = (bool) (substr($SeekTableSignatureTest, 4, 8) == 'SHNAMPSK');
     if ($info['shn']['seektable']['present']) {
         $info['shn']['seektable']['length'] = Helper::LittleEndian2Int(substr($SeekTableSignatureTest, 0, 4));
         $info['shn']['seektable']['offset'] = $info['avdataend'] - $info['shn']['seektable']['length'];
         fseek($this->getid3->fp, $info['shn']['seektable']['offset'], SEEK_SET);
         $SeekTableMagic = fread($this->getid3->fp, 4);
         $magic = 'SEEK';
         if ($SeekTableMagic != $magic) {
             $info['error'][] = 'Expecting "' . Helper::PrintHexBytes($magic) . '" at offset ' . $info['shn']['seektable']['offset'] . ', found "' . Helper::PrintHexBytes($SeekTableMagic) . '"';
             return false;
         } else {
             // typedef struct tag_TSeekEntry
             // {
             //   unsigned long SampleNumber;
             //   unsigned long SHNFileByteOffset;
             //   unsigned long SHNLastBufferReadPosition;
             //   unsigned short SHNByteGet;
             //   unsigned short SHNBufferOffset;
             //   unsigned short SHNFileBitOffset;
             //   unsigned long SHNGBuffer;
             //   unsigned short SHNBitShift;
             //   long CBuf0[3];
             //   long CBuf1[3];
             //   long Offset0[4];
             //   long Offset1[4];
             // }TSeekEntry;
             $SeekTableData = fread($this->getid3->fp, $info['shn']['seektable']['length'] - 16);
             $info['shn']['seektable']['entry_count'] = floor(strlen($SeekTableData) / 80);
             //$info['shn']['seektable']['entries'] = array();
             //$SeekTableOffset = 0;
             //for ($i = 0; $i < $info['shn']['seektable']['entry_count']; $i++) {
             //	$SeekTableEntry['sample_number'] = GetId3_lib::LittleEndian2Int(substr($SeekTableData, $SeekTableOffset, 4));
             //	$SeekTableOffset += 4;
             //	$SeekTableEntry['shn_file_byte_offset'] = GetId3_lib::LittleEndian2Int(substr($SeekTableData, $SeekTableOffset, 4));
             //	$SeekTableOffset += 4;
             //	$SeekTableEntry['shn_last_buffer_read_position'] = GetId3_lib::LittleEndian2Int(substr($SeekTableData, $SeekTableOffset, 4));
             //	$SeekTableOffset += 4;
             //	$SeekTableEntry['shn_byte_get'] = GetId3_lib::LittleEndian2Int(substr($SeekTableData, $SeekTableOffset, 2));
             //	$SeekTableOffset += 2;
             //	$SeekTableEntry['shn_buffer_offset'] = GetId3_lib::LittleEndian2Int(substr($SeekTableData, $SeekTableOffset, 2));
             //	$SeekTableOffset += 2;
             //	$SeekTableEntry['shn_file_bit_offset'] = GetId3_lib::LittleEndian2Int(substr($SeekTableData, $SeekTableOffset, 2));
             //	$SeekTableOffset += 2;
             //	$SeekTableEntry['shn_gbuffer'] = GetId3_lib::LittleEndian2Int(substr($SeekTableData, $SeekTableOffset, 4));
             //	$SeekTableOffset += 4;
             //	$SeekTableEntry['shn_bit_shift'] = GetId3_lib::LittleEndian2Int(substr($SeekTableData, $SeekTableOffset, 2));
             //	$SeekTableOffset += 2;
             //	for ($j = 0; $j < 3; $j++) {
             //		$SeekTableEntry['cbuf0'][$j] = GetId3_lib::LittleEndian2Int(substr($SeekTableData, $SeekTableOffset, 4));
             //		$SeekTableOffset += 4;
             //	}
             //	for ($j = 0; $j < 3; $j++) {
             //		$SeekTableEntry['cbuf1'][$j] = GetId3_lib::LittleEndian2Int(substr($SeekTableData, $SeekTableOffset, 4));
             //		$SeekTableOffset += 4;
             //	}
             //	for ($j = 0; $j < 4; $j++) {
             //		$SeekTableEntry['offset0'][$j] = GetId3_lib::LittleEndian2Int(substr($SeekTableData, $SeekTableOffset, 4));
             //		$SeekTableOffset += 4;
             //	}
             //	for ($j = 0; $j < 4; $j++) {
             //		$SeekTableEntry['offset1'][$j] = GetId3_lib::LittleEndian2Int(substr($SeekTableData, $SeekTableOffset, 4));
             //		$SeekTableOffset += 4;
             //	}
             //
             //	$info['shn']['seektable']['entries'][] = $SeekTableEntry;
             //}
         }
     }
     if (preg_match('#(1|ON)#i', ini_get('safe_mode'))) {
         $info['error'][] = 'PHP running in Safe Mode - backtick operator not available, cannot run shntool to analyze Shorten files';
         return false;
     }
     if (GetId3Core::environmentIsWindows()) {
         $RequiredFiles = array('shorten.exe', 'cygwin1.dll', 'head.exe');
         foreach ($RequiredFiles as $required_file) {
             if (!is_readable(GetId3Core::getHelperAppsDir() . $required_file)) {
                 $info['error'][] = GetId3Core::getHelperAppsDir() . $required_file . ' does not exist';
                 return false;
             }
         }
         $commandline = GetId3Core::getHelperAppsDir() . 'shorten.exe -x "' . $info['filenamepath'] . '" - | ' . GetId3Core::getHelperAppsDir() . 'head.exe -c 64';
         $commandline = str_replace('/', '\\', $commandline);
     } else {
         static $shorten_present;
         if (!isset($shorten_present)) {
             $shorten_present = file_exists('/usr/local/bin/shorten') || `which shorten`;
         }
         if (!$shorten_present) {
             $info['error'][] = 'shorten binary was not found in path or /usr/local/bin';
             return false;
         }
         $commandline = (file_exists('/usr/local/bin/shorten') ? '/usr/local/bin/' : '') . 'shorten -x ' . escapeshellarg($info['filenamepath']) . ' - | head -c 64';
     }
     $output = `{$commandline}`;
     if (!empty($output) && substr($output, 12, 4) == 'fmt ') {
         $fmt_size = Helper::LittleEndian2Int(substr($output, 16, 4));
         $DecodedWAVFORMATEX = Riff::RIFFparseWAVEFORMATex(substr($output, 20, $fmt_size));
         $info['audio']['channels'] = $DecodedWAVFORMATEX['channels'];
         $info['audio']['bits_per_sample'] = $DecodedWAVFORMATEX['bits_per_sample'];
         $info['audio']['sample_rate'] = $DecodedWAVFORMATEX['sample_rate'];
         if (substr($output, 20 + $fmt_size, 4) == 'data') {
             $info['playtime_seconds'] = Helper::LittleEndian2Int(substr($output, 20 + 4 + $fmt_size, 4)) / $DecodedWAVFORMATEX['raw']['nAvgBytesPerSec'];
         } else {
             $info['error'][] = 'shorten failed to decode DATA chunk to expected location, cannot determine playtime';
             return false;
         }
         $info['audio']['bitrate'] = ($info['avdataend'] - $info['avdataoffset']) / $info['playtime_seconds'] * 8;
     } else {
         $info['error'][] = 'shorten failed to decode file to WAV for parsing';
         return false;
     }
     return true;
 }