2 /////////////////////////////////////////////////////////////////
3 /// getID3() by James Heinrich <info@getid3.org> //
4 // available at http://getid3.sourceforge.net //
5 // or http://www.getid3.org //
6 // also https://github.com/JamesHeinrich/getID3 //
7 /////////////////////////////////////////////////////////////////
9 // Please see readme.txt for more information //
11 /////////////////////////////////////////////////////////////////
13 // define a constant rather than looking up every time it is needed
14 if (!defined('GETID3_OS_ISWINDOWS')) {
15 define('GETID3_OS_ISWINDOWS', (stripos(PHP_OS, 'WIN') === 0));
17 // Get base path of getID3() - ONCE
18 if (!defined('GETID3_INCLUDEPATH')) {
19 define('GETID3_INCLUDEPATH', dirname(__FILE__).DIRECTORY_SEPARATOR);
21 // Workaround Bug #39923 (https://bugs.php.net/bug.php?id=39923)
22 if (!defined('IMG_JPG') && defined('IMAGETYPE_JPEG')) {
23 define('IMG_JPG', IMAGETYPE_JPEG);
26 // attempt to define temp dir as something flexible but reliable
27 $temp_dir = ini_get('upload_tmp_dir');
28 if ($temp_dir && (!is_dir($temp_dir) || !is_readable($temp_dir))) {
31 if (!$temp_dir && function_exists('sys_get_temp_dir')) { // sys_get_temp_dir added in PHP v5.2.1
32 // sys_get_temp_dir() may give inaccessible temp dir, e.g. with open_basedir on virtual hosts
33 $temp_dir = sys_get_temp_dir();
35 $temp_dir = @realpath($temp_dir); // see https://github.com/JamesHeinrich/getID3/pull/10
36 $open_basedir = ini_get('open_basedir');
38 // e.g. "/var/www/vhosts/getid3.org/httpdocs/:/tmp/"
39 $temp_dir = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $temp_dir);
40 $open_basedir = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $open_basedir);
41 if (substr($temp_dir, -1, 1) != DIRECTORY_SEPARATOR) {
42 $temp_dir .= DIRECTORY_SEPARATOR;
44 $found_valid_tempdir = false;
45 $open_basedirs = explode(PATH_SEPARATOR, $open_basedir);
46 foreach ($open_basedirs as $basedir) {
47 if (substr($basedir, -1, 1) != DIRECTORY_SEPARATOR) {
48 $basedir .= DIRECTORY_SEPARATOR;
50 if (preg_match('#^'.preg_quote($basedir).'#', $temp_dir)) {
51 $found_valid_tempdir = true;
55 if (!$found_valid_tempdir) {
58 unset($open_basedirs, $found_valid_tempdir, $basedir);
61 $temp_dir = '*'; // invalid directory name should force tempnam() to use system default temp dir
63 // $temp_dir = '/something/else/'; // feel free to override temp dir here if it works better for your system
64 if (!defined('GETID3_TEMP_DIR')) {
65 define('GETID3_TEMP_DIR', $temp_dir);
67 unset($open_basedir, $temp_dir);
75 public $encoding = 'UTF-8'; // CASE SENSITIVE! - i.e. (must be supported by iconv()). Examples: ISO-8859-1 UTF-8 UTF-16 UTF-16BE
76 public $encoding_id3v1 = 'ISO-8859-1'; // Should always be 'ISO-8859-1', but some tags may be written in other encodings such as 'EUC-CN' or 'CP1252'
78 // public: Optional tag checks - disable for speed.
79 public $option_tag_id3v1 = true; // Read and process ID3v1 tags
80 public $option_tag_id3v2 = true; // Read and process ID3v2 tags
81 public $option_tag_lyrics3 = true; // Read and process Lyrics3 tags
82 public $option_tag_apetag = true; // Read and process APE tags
83 public $option_tags_process = true; // Copy tags to root key 'tags' and encode to $this->encoding
84 public $option_tags_html = true; // Copy tags to root key 'tags_html' properly translated from various encodings to HTML entities
86 // public: Optional tag/comment calucations
87 public $option_extra_info = true; // Calculate additional info such as bitrate, channelmode etc
89 // public: Optional handling of embedded attachments (e.g. images)
90 public $option_save_attachments = true; // defaults to true (ATTACHMENTS_INLINE) for backward compatibility
92 // public: Optional calculations
93 public $option_md5_data = false; // Get MD5 sum of data part - slow
94 public $option_md5_data_source = false; // Use MD5 of source file if availble - only FLAC and OptimFROG
95 public $option_sha1_data = false; // Get SHA1 sum of data part - slow
96 public $option_max_2gb_check = null; // Check whether file is larger than 2GB and thus not supported by 32-bit PHP (null: auto-detect based on PHP_INT_MAX)
98 // public: Read buffer size in bytes
99 public $option_fread_buffer_size = 32768;
102 public $filename; // Filename of file being analysed.
103 public $fp; // Filepointer to file being analysed.
104 public $info; // Result array.
105 public $tempdir = GETID3_TEMP_DIR;
106 public $memory_limit = 0;
108 // Protected variables
109 protected $startup_error = '';
110 protected $startup_warning = '';
112 const VERSION = '1.9.9-20141121';
113 const FREAD_BUFFER_SIZE = 32768;
115 const ATTACHMENTS_NONE = false;
116 const ATTACHMENTS_INLINE = true;
118 // public: constructor
119 public function __construct() {
122 $this->memory_limit = ini_get('memory_limit');
123 if (preg_match('#([0-9]+)M#i', $this->memory_limit, $matches)) {
124 // could be stored as "16M" rather than 16777216 for example
125 $this->memory_limit = $matches[1] * 1048576;
126 } elseif (preg_match('#([0-9]+)G#i', $this->memory_limit, $matches)) { // The 'G' modifier is available since PHP 5.1.0
127 // could be stored as "2G" rather than 2147483648 for example
128 $this->memory_limit = $matches[1] * 1073741824;
130 if ($this->memory_limit <= 0) {
131 // memory limits probably disabled
132 } elseif ($this->memory_limit <= 4194304) {
133 $this->startup_error .= 'PHP has less than 4MB available memory and will very likely run out. Increase memory_limit in php.ini';
134 } elseif ($this->memory_limit <= 12582912) {
135 $this->startup_warning .= 'PHP has less than 12MB available memory and might run out if all modules are loaded. Increase memory_limit in php.ini';
138 // Check safe_mode off
139 if (preg_match('#(1|ON)#i', ini_get('safe_mode'))) {
140 $this->warning('WARNING: Safe mode is on, shorten support disabled, md5data/sha1data for ogg vorbis disabled, ogg vorbos/flac tag writing disabled.');
143 if (intval(ini_get('mbstring.func_overload')) > 0) {
144 $this->warning('WARNING: php.ini contains "mbstring.func_overload = '.ini_get('mbstring.func_overload').'", this may break things.');
147 // Check for magic_quotes_runtime
148 if (function_exists('get_magic_quotes_runtime')) {
149 if (get_magic_quotes_runtime()) {
150 return $this->startup_error('magic_quotes_runtime must be disabled before running getID3(). Surround getid3 block by set_magic_quotes_runtime(0) and set_magic_quotes_runtime(1).');
154 // Check for magic_quotes_gpc
155 if (function_exists('magic_quotes_gpc')) {
156 if (get_magic_quotes_gpc()) {
157 return $this->startup_error('magic_quotes_gpc must be disabled before running getID3(). Surround getid3 block by set_magic_quotes_gpc(0) and set_magic_quotes_gpc(1).');
161 // Load support library
162 if (!include_once(GETID3_INCLUDEPATH.'getid3.lib.php')) {
163 $this->startup_error .= 'getid3.lib.php is missing or corrupt';
166 if ($this->option_max_2gb_check === null) {
167 $this->option_max_2gb_check = (PHP_INT_MAX <= 2147483647);
171 // Needed for Windows only:
172 // Define locations of helper applications for Shorten, VorbisComment, MetaFLAC
173 // as well as other helper functions such as head, tail, md5sum, etc
174 // This path cannot contain spaces, but the below code will attempt to get the
175 // 8.3-equivalent path automatically
176 // IMPORTANT: This path must include the trailing slash
177 if (GETID3_OS_ISWINDOWS && !defined('GETID3_HELPERAPPSDIR')) {
179 $helperappsdir = GETID3_INCLUDEPATH.'..'.DIRECTORY_SEPARATOR.'helperapps'; // must not have any space in this path
181 if (!is_dir($helperappsdir)) {
182 $this->startup_warning .= '"'.$helperappsdir.'" cannot be defined as GETID3_HELPERAPPSDIR because it does not exist';
183 } elseif (strpos(realpath($helperappsdir), ' ') !== false) {
184 $DirPieces = explode(DIRECTORY_SEPARATOR, realpath($helperappsdir));
185 $path_so_far = array();
186 foreach ($DirPieces as $key => $value) {
187 if (strpos($value, ' ') !== false) {
188 if (!empty($path_so_far)) {
189 $commandline = 'dir /x '.escapeshellarg(implode(DIRECTORY_SEPARATOR, $path_so_far));
190 $dir_listing = `$commandline`;
191 $lines = explode("\n", $dir_listing);
192 foreach ($lines as $line) {
194 if (preg_match('#^([0-9/]{10}) +([0-9:]{4,5}( [AP]M)?) +(<DIR>|[0-9,]+) +([^ ]{0,11}) +(.+)$#', $line, $matches)) {
195 list($dummy, $date, $time, $ampm, $filesize, $shortname, $filename) = $matches;
196 if ((strtoupper($filesize) == '<DIR>') && (strtolower($filename) == strtolower($value))) {
202 $this->startup_warning .= 'GETID3_HELPERAPPSDIR must not have any spaces in it - use 8dot3 naming convention if neccesary. You can run "dir /x" from the commandline to see the correct 8.3-style names.';
205 $path_so_far[] = $value;
207 $helperappsdir = implode(DIRECTORY_SEPARATOR, $path_so_far);
209 define('GETID3_HELPERAPPSDIR', $helperappsdir.DIRECTORY_SEPARATOR);
215 public function version() {
216 return self::VERSION;
219 public function fread_buffer_size() {
220 return $this->option_fread_buffer_size;
225 public function setOption($optArray) {
226 if (!is_array($optArray) || empty($optArray)) {
229 foreach ($optArray as $opt => $val) {
230 if (isset($this->$opt) === false) {
239 public function openfile($filename) {
241 if (!empty($this->startup_error)) {
242 throw new getid3_exception($this->startup_error);
244 if (!empty($this->startup_warning)) {
245 $this->warning($this->startup_warning);
248 // init result array and set parameters
249 $this->filename = $filename;
250 $this->info = array();
251 $this->info['GETID3_VERSION'] = $this->version();
252 $this->info['php_memory_limit'] = (($this->memory_limit > 0) ? $this->memory_limit : false);
254 // remote files not supported
255 if (preg_match('/^(ht|f)tp:\/\//', $filename)) {
256 throw new getid3_exception('Remote files are not supported - please copy the file locally first');
259 $filename = str_replace('/', DIRECTORY_SEPARATOR, $filename);
260 $filename = preg_replace('#(.+)'.preg_quote(DIRECTORY_SEPARATOR).'{2,}#U', '\1'.DIRECTORY_SEPARATOR, $filename);
263 //if (is_readable($filename) && is_file($filename) && ($this->fp = fopen($filename, 'rb'))) { // see http://www.getid3.org/phpBB3/viewtopic.php?t=1720
264 if ((is_readable($filename) || file_exists($filename)) && is_file($filename) && ($this->fp = fopen($filename, 'rb'))) {
267 $errormessagelist = array();
268 if (!is_readable($filename)) {
269 $errormessagelist[] = '!is_readable';
271 if (!is_file($filename)) {
272 $errormessagelist[] = '!is_file';
274 if (!file_exists($filename)) {
275 $errormessagelist[] = '!file_exists';
277 if (empty($errormessagelist)) {
278 $errormessagelist[] = 'fopen failed';
280 throw new getid3_exception('Could not open "'.$filename.'" ('.implode('; ', $errormessagelist).')');
283 $this->info['filesize'] = filesize($filename);
284 // set redundant parameters - might be needed in some include file
285 // filenames / filepaths in getID3 are always expressed with forward slashes (unix-style) for both Windows and other to try and minimize confusion
286 $filename = str_replace('\\', '/', $filename);
287 $this->info['filepath'] = str_replace('\\', '/', realpath(dirname($filename)));
288 $this->info['filename'] = getid3_lib::mb_basename($filename);
289 $this->info['filenamepath'] = $this->info['filepath'].'/'.$this->info['filename'];
292 // option_max_2gb_check
293 if ($this->option_max_2gb_check) {
294 // PHP (32-bit all, and 64-bit Windows) doesn't support integers larger than 2^31 (~2GB)
295 // filesize() simply returns (filesize % (pow(2, 32)), no matter the actual filesize
296 // ftell() returns 0 if seeking to the end is beyond the range of unsigned integer
297 $fseek = fseek($this->fp, 0, SEEK_END);
298 if (($fseek < 0) || (($this->info['filesize'] != 0) && (ftell($this->fp) == 0)) ||
299 ($this->info['filesize'] < 0) ||
300 (ftell($this->fp) < 0)) {
301 $real_filesize = getid3_lib::getFileSizeSyscall($this->info['filenamepath']);
303 if ($real_filesize === false) {
304 unset($this->info['filesize']);
306 throw new getid3_exception('Unable to determine actual filesize. File is most likely larger than '.round(PHP_INT_MAX / 1073741824).'GB and is not supported by PHP.');
307 } elseif (getid3_lib::intValueSupported($real_filesize)) {
308 unset($this->info['filesize']);
310 throw new getid3_exception('PHP seems to think the file is larger than '.round(PHP_INT_MAX / 1073741824).'GB, but filesystem reports it as '.number_format($real_filesize, 3).'GB, please report to info@getid3.org');
312 $this->info['filesize'] = $real_filesize;
313 $this->warning('File is larger than '.round(PHP_INT_MAX / 1073741824).'GB (filesystem reports it as '.number_format($real_filesize, 3).'GB) and is not properly supported by PHP.');
317 // set more parameters
318 $this->info['avdataoffset'] = 0;
319 $this->info['avdataend'] = $this->info['filesize'];
320 $this->info['fileformat'] = ''; // filled in later
321 $this->info['audio']['dataformat'] = ''; // filled in later, unset if not used
322 $this->info['video']['dataformat'] = ''; // filled in later, unset if not used
323 $this->info['tags'] = array(); // filled in later, unset if not used
324 $this->info['error'] = array(); // filled in later, unset if not used
325 $this->info['warning'] = array(); // filled in later, unset if not used
326 $this->info['comments'] = array(); // filled in later, unset if not used
327 $this->info['encoding'] = $this->encoding; // required by id3v2 and iso modules - can be unset at the end if desired
331 } catch (Exception $e) {
332 $this->error($e->getMessage());
337 // public: analyze file
338 public function analyze($filename) {
340 if (!$this->openfile($filename)) {
345 foreach (array('id3v2'=>'id3v2', 'id3v1'=>'id3v1', 'apetag'=>'ape', 'lyrics3'=>'lyrics3') as $tag_name => $tag_key) {
346 $option_tag = 'option_tag_'.$tag_name;
347 if ($this->$option_tag) {
348 $this->include_module('tag.'.$tag_name);
350 $tag_class = 'getid3_'.$tag_name;
351 $tag = new $tag_class($this);
354 catch (getid3_exception $e) {
359 if (isset($this->info['id3v2']['tag_offset_start'])) {
360 $this->info['avdataoffset'] = max($this->info['avdataoffset'], $this->info['id3v2']['tag_offset_end']);
362 foreach (array('id3v1'=>'id3v1', 'apetag'=>'ape', 'lyrics3'=>'lyrics3') as $tag_name => $tag_key) {
363 if (isset($this->info[$tag_key]['tag_offset_start'])) {
364 $this->info['avdataend'] = min($this->info['avdataend'], $this->info[$tag_key]['tag_offset_start']);
368 // ID3v2 detection (NOT parsing), even if ($this->option_tag_id3v2 == false) done to make fileformat easier
369 if (!$this->option_tag_id3v2) {
371 $header = fread($this->fp, 10);
372 if ((substr($header, 0, 3) == 'ID3') && (strlen($header) == 10)) {
373 $this->info['id3v2']['header'] = true;
374 $this->info['id3v2']['majorversion'] = ord($header{3});
375 $this->info['id3v2']['minorversion'] = ord($header{4});
376 $this->info['avdataoffset'] += getid3_lib::BigEndian2Int(substr($header, 6, 4), 1) + 10; // length of ID3v2 tag in 10-byte header doesn't include 10-byte header length
380 // read 32 kb file data
381 fseek($this->fp, $this->info['avdataoffset']);
382 $formattest = fread($this->fp, 32774);
385 $determined_format = $this->GetFileFormat($formattest, $filename);
387 // unable to determine file format
388 if (!$determined_format) {
390 return $this->error('unable to determine file format');
393 // check for illegal ID3 tags
394 if (isset($determined_format['fail_id3']) && (in_array('id3v1', $this->info['tags']) || in_array('id3v2', $this->info['tags']))) {
395 if ($determined_format['fail_id3'] === 'ERROR') {
397 return $this->error('ID3 tags not allowed on this file type.');
398 } elseif ($determined_format['fail_id3'] === 'WARNING') {
399 $this->warning('ID3 tags not allowed on this file type.');
403 // check for illegal APE tags
404 if (isset($determined_format['fail_ape']) && in_array('ape', $this->info['tags'])) {
405 if ($determined_format['fail_ape'] === 'ERROR') {
407 return $this->error('APE tags not allowed on this file type.');
408 } elseif ($determined_format['fail_ape'] === 'WARNING') {
409 $this->warning('APE tags not allowed on this file type.');
414 $this->info['mime_type'] = $determined_format['mime_type'];
416 // supported format signature pattern detected, but module deleted
417 if (!file_exists(GETID3_INCLUDEPATH.$determined_format['include'])) {
419 return $this->error('Format not supported, module "'.$determined_format['include'].'" was removed.');
422 // module requires iconv support
423 // Check encoding/iconv support
424 if (!empty($determined_format['iconv_req']) && !function_exists('iconv') && !in_array($this->encoding, array('ISO-8859-1', 'UTF-8', 'UTF-16LE', 'UTF-16BE', 'UTF-16'))) {
425 $errormessage = 'iconv() support is required for this module ('.$determined_format['include'].') for encodings other than ISO-8859-1, UTF-8, UTF-16LE, UTF16-BE, UTF-16. ';
426 if (GETID3_OS_ISWINDOWS) {
427 $errormessage .= 'PHP does not have iconv() support. Please enable php_iconv.dll in php.ini, and copy iconv.dll from c:/php/dlls to c:/windows/system32';
429 $errormessage .= 'PHP is not compiled with iconv() support. Please recompile with the --with-iconv switch';
431 return $this->error($errormessage);
435 include_once(GETID3_INCLUDEPATH.$determined_format['include']);
437 // instantiate module class
438 $class_name = 'getid3_'.$determined_format['module'];
439 if (!class_exists($class_name)) {
440 return $this->error('Format not supported, module "'.$determined_format['include'].'" is corrupt.');
442 $class = new $class_name($this);
449 // process all tags - copy to 'tags' and convert charsets
450 if ($this->option_tags_process) {
451 $this->HandleAllTags();
454 // perform more calculations
455 if ($this->option_extra_info) {
456 $this->ChannelsBitratePlaytimeCalculations();
457 $this->CalculateCompressionRatioVideo();
458 $this->CalculateCompressionRatioAudio();
459 $this->CalculateReplayGain();
460 $this->ProcessAudioStreams();
463 // get the MD5 sum of the audio/video portion of the file - without ID3/APE/Lyrics3/etc header/footer tags
464 if ($this->option_md5_data) {
465 // do not calc md5_data if md5_data_source is present - set by flac only - future MPC/SV8 too
466 if (!$this->option_md5_data_source || empty($this->info['md5_data_source'])) {
467 $this->getHashdata('md5');
471 // get the SHA1 sum of the audio/video portion of the file - without ID3/APE/Lyrics3/etc header/footer tags
472 if ($this->option_sha1_data) {
473 $this->getHashdata('sha1');
476 // remove undesired keys
479 } catch (Exception $e) {
480 $this->error('Caught exception: '.$e->getMessage());
488 // private: error handling
489 public function error($message) {
491 if (!isset($this->info['error'])) {
492 $this->info['error'] = array();
494 $this->info['error'][] = $message;
499 // private: warning handling
500 public function warning($message) {
501 $this->info['warning'][] = $message;
507 private function CleanUp() {
509 // remove possible empty keys
510 $AVpossibleEmptyKeys = array('dataformat', 'bits_per_sample', 'encoder_options', 'streams', 'bitrate');
511 foreach ($AVpossibleEmptyKeys as $dummy => $key) {
512 if (empty($this->info['audio'][$key]) && isset($this->info['audio'][$key])) {
513 unset($this->info['audio'][$key]);
515 if (empty($this->info['video'][$key]) && isset($this->info['video'][$key])) {
516 unset($this->info['video'][$key]);
520 // remove empty root keys
521 if (!empty($this->info)) {
522 foreach ($this->info as $key => $value) {
523 if (empty($this->info[$key]) && ($this->info[$key] !== 0) && ($this->info[$key] !== '0')) {
524 unset($this->info[$key]);
529 // remove meaningless entries from unknown-format files
530 if (empty($this->info['fileformat'])) {
531 if (isset($this->info['avdataoffset'])) {
532 unset($this->info['avdataoffset']);
534 if (isset($this->info['avdataend'])) {
535 unset($this->info['avdataend']);
539 // remove possible duplicated identical entries
540 if (!empty($this->info['error'])) {
541 $this->info['error'] = array_values(array_unique($this->info['error']));
543 if (!empty($this->info['warning'])) {
544 $this->info['warning'] = array_values(array_unique($this->info['warning']));
547 // remove "global variable" type keys
548 unset($this->info['php_memory_limit']);
554 // return array containing information about all supported formats
555 public function GetFileFormatArray() {
556 static $format_info = array();
557 if (empty($format_info)) {
558 $format_info = array(
562 // AC-3 - audio - Dolby AC-3 / Dolby Digital
564 'pattern' => '^\x0B\x77',
567 'mime_type' => 'audio/ac3',
570 // AAC - audio - Advanced Audio Coding (AAC) - ADIF format
572 'pattern' => '^ADIF',
575 'mime_type' => 'application/octet-stream',
576 'fail_ape' => 'WARNING',
580 // AA - audio - Audible Audiobook
582 'pattern' => '^.{4}\x57\x90\x75\x36',
585 'mime_type' => 'audio/audible',
588 // AAC - audio - Advanced Audio Coding (AAC) - ADTS format (very similar to MP3)
590 'pattern' => '^\xFF[\xF0-\xF1\xF8-\xF9]',
593 'mime_type' => 'application/octet-stream',
594 'fail_ape' => 'WARNING',
598 // AU - audio - NeXT/Sun AUdio (AU)
600 'pattern' => '^\.snd',
603 'mime_type' => 'audio/basic',
606 // AMR - audio - Adaptive Multi Rate
608 'pattern' => '^\x23\x21AMR\x0A', // #!AMR[0A]
611 'mime_type' => 'audio/amr',
614 // AVR - audio - Audio Visual Research
616 'pattern' => '^2BIT',
619 'mime_type' => 'application/octet-stream',
622 // BONK - audio - Bonk v0.9+
624 'pattern' => '^\x00(BONK|INFO|META| ID3)',
627 'mime_type' => 'audio/xmms-bonk',
630 // DSS - audio - Digital Speech Standard
632 'pattern' => '^[\x02-\x03]ds[s2]',
635 'mime_type' => 'application/octet-stream',
638 // DTS - audio - Dolby Theatre System
640 'pattern' => '^\x7F\xFE\x80\x01',
643 'mime_type' => 'audio/dts',
646 // FLAC - audio - Free Lossless Audio Codec
648 'pattern' => '^fLaC',
651 'mime_type' => 'audio/x-flac',
654 // LA - audio - Lossless Audio (LA)
656 'pattern' => '^LA0[2-4]',
659 'mime_type' => 'application/octet-stream',
662 // LPAC - audio - Lossless Predictive Audio Compression (LPAC)
664 'pattern' => '^LPAC',
667 'mime_type' => 'application/octet-stream',
670 // MIDI - audio - MIDI (Musical Instrument Digital Interface)
672 'pattern' => '^MThd',
675 'mime_type' => 'audio/midi',
678 // MAC - audio - Monkey's Audio Compressor
680 'pattern' => '^MAC ',
682 'module' => 'monkey',
683 'mime_type' => 'application/octet-stream',
686 // has been known to produce false matches in random files (e.g. JPEGs), leave out until more precise matching available
687 // // MOD - audio - MODule (assorted sub-formats)
689 // 'pattern' => '^.{1080}(M\\.K\\.|M!K!|FLT4|FLT8|[5-9]CHN|[1-3][0-9]CH)',
690 // 'group' => 'audio',
691 // 'module' => 'mod',
692 // 'option' => 'mod',
693 // 'mime_type' => 'audio/mod',
696 // MOD - audio - MODule (Impulse Tracker)
698 'pattern' => '^IMPM',
702 'mime_type' => 'audio/it',
705 // MOD - audio - MODule (eXtended Module, various sub-formats)
707 'pattern' => '^Extended Module',
711 'mime_type' => 'audio/xm',
714 // MOD - audio - MODule (ScreamTracker)
716 'pattern' => '^.{44}SCRM',
720 'mime_type' => 'audio/s3m',
723 // MPC - audio - Musepack / MPEGplus
725 'pattern' => '^(MPCK|MP\+|[\x00\x01\x10\x11\x40\x41\x50\x51\x80\x81\x90\x91\xC0\xC1\xD0\xD1][\x20-37][\x00\x20\x40\x60\x80\xA0\xC0\xE0])',
728 'mime_type' => 'audio/x-musepack',
731 // MP3 - audio - MPEG-audio Layer 3 (very similar to AAC-ADTS)
733 'pattern' => '^\xFF[\xE2-\xE7\xF2-\xF7\xFA-\xFF][\x00-\x0B\x10-\x1B\x20-\x2B\x30-\x3B\x40-\x4B\x50-\x5B\x60-\x6B\x70-\x7B\x80-\x8B\x90-\x9B\xA0-\xAB\xB0-\xBB\xC0-\xCB\xD0-\xDB\xE0-\xEB\xF0-\xFB]',
736 'mime_type' => 'audio/mpeg',
739 // OFR - audio - OptimFROG
741 'pattern' => '^(\*RIFF|OFR)',
743 'module' => 'optimfrog',
744 'mime_type' => 'application/octet-stream',
747 // RKAU - audio - RKive AUdio compressor
752 'mime_type' => 'application/octet-stream',
755 // SHN - audio - Shorten
757 'pattern' => '^ajkg',
759 'module' => 'shorten',
760 'mime_type' => 'audio/xmms-shn',
761 'fail_id3' => 'ERROR',
762 'fail_ape' => 'ERROR',
765 // TTA - audio - TTA Lossless Audio Compressor (http://tta.corecodec.org)
767 'pattern' => '^TTA', // could also be '^TTA(\x01|\x02|\x03|2|1)'
770 'mime_type' => 'application/octet-stream',
773 // VOC - audio - Creative Voice (VOC)
775 'pattern' => '^Creative Voice File',
778 'mime_type' => 'audio/voc',
781 // VQF - audio - transform-domain weighted interleave Vector Quantization Format (VQF)
783 'pattern' => '^TWIN',
786 'mime_type' => 'application/octet-stream',
789 // WV - audio - WavPack (v4.0+)
791 'pattern' => '^wvpk',
793 'module' => 'wavpack',
794 'mime_type' => 'application/octet-stream',
798 // Audio-Video formats
800 // ASF - audio/video - Advanced Streaming Format, Windows Media Video, Windows Media Audio
802 'pattern' => '^\x30\x26\xB2\x75\x8E\x66\xCF\x11\xA6\xD9\x00\xAA\x00\x62\xCE\x6C',
803 'group' => 'audio-video',
805 'mime_type' => 'video/x-ms-asf',
806 'iconv_req' => false,
809 // BINK - audio/video - Bink / Smacker
811 'pattern' => '^(BIK|SMK)',
812 'group' => 'audio-video',
814 'mime_type' => 'application/octet-stream',
817 // FLV - audio/video - FLash Video
819 'pattern' => '^FLV\x01',
820 'group' => 'audio-video',
822 'mime_type' => 'video/x-flv',
825 // MKAV - audio/video - Mastroka
827 'pattern' => '^\x1A\x45\xDF\xA3',
828 'group' => 'audio-video',
829 'module' => 'matroska',
830 'mime_type' => 'video/x-matroska', // may also be audio/x-matroska
833 // MPEG - audio/video - MPEG (Moving Pictures Experts Group)
835 'pattern' => '^\x00\x00\x01(\xBA|\xB3)',
836 'group' => 'audio-video',
838 'mime_type' => 'video/mpeg',
841 // NSV - audio/video - Nullsoft Streaming Video (NSV)
843 'pattern' => '^NSV[sf]',
844 'group' => 'audio-video',
846 'mime_type' => 'application/octet-stream',
849 // Ogg - audio/video - Ogg (Ogg-Vorbis, Ogg-FLAC, Speex, Ogg-Theora(*), Ogg-Tarkin(*))
851 'pattern' => '^OggS',
854 'mime_type' => 'application/ogg',
855 'fail_id3' => 'WARNING',
856 'fail_ape' => 'WARNING',
859 // QT - audio/video - Quicktime
860 'quicktime' => array(
861 'pattern' => '^.{4}(cmov|free|ftyp|mdat|moov|pnot|skip|wide)',
862 'group' => 'audio-video',
863 'module' => 'quicktime',
864 'mime_type' => 'video/quicktime',
867 // RIFF - audio/video - Resource Interchange File Format (RIFF) / WAV / AVI / CD-audio / SDSS = renamed variant used by SmartSound QuickTracks (www.smartsound.com) / FORM = Audio Interchange File Format (AIFF)
869 'pattern' => '^(RIFF|SDSS|FORM)',
870 'group' => 'audio-video',
872 'mime_type' => 'audio/x-wave',
873 'fail_ape' => 'WARNING',
876 // Real - audio/video - RealAudio, RealVideo
878 'pattern' => '^(\\.RMF|\\.ra)',
879 'group' => 'audio-video',
881 'mime_type' => 'audio/x-realaudio',
884 // SWF - audio/video - ShockWave Flash
886 'pattern' => '^(F|C)WS',
887 'group' => 'audio-video',
889 'mime_type' => 'application/x-shockwave-flash',
892 // TS - audio/video - MPEG-2 Transport Stream
894 'pattern' => '^(\x47.{187}){10,}', // packets are 188 bytes long and start with 0x47 "G". Check for at least 10 packets matching this pattern
895 'group' => 'audio-video',
897 'mime_type' => 'video/MP2T',
901 // Still-Image formats
903 // BMP - still image - Bitmap (Windows, OS/2; uncompressed, RLE8, RLE4)
906 'group' => 'graphic',
908 'mime_type' => 'image/bmp',
909 'fail_id3' => 'ERROR',
910 'fail_ape' => 'ERROR',
913 // GIF - still image - Graphics Interchange Format
916 'group' => 'graphic',
918 'mime_type' => 'image/gif',
919 'fail_id3' => 'ERROR',
920 'fail_ape' => 'ERROR',
923 // JPEG - still image - Joint Photographic Experts Group (JPEG)
925 'pattern' => '^\xFF\xD8\xFF',
926 'group' => 'graphic',
928 'mime_type' => 'image/jpeg',
929 'fail_id3' => 'ERROR',
930 'fail_ape' => 'ERROR',
933 // PCD - still image - Kodak Photo CD
935 'pattern' => '^.{2048}PCD_IPI\x00',
936 'group' => 'graphic',
938 'mime_type' => 'image/x-photo-cd',
939 'fail_id3' => 'ERROR',
940 'fail_ape' => 'ERROR',
944 // PNG - still image - Portable Network Graphics (PNG)
946 'pattern' => '^\x89\x50\x4E\x47\x0D\x0A\x1A\x0A',
947 'group' => 'graphic',
949 'mime_type' => 'image/png',
950 'fail_id3' => 'ERROR',
951 'fail_ape' => 'ERROR',
955 // SVG - still image - Scalable Vector Graphics (SVG)
957 'pattern' => '(<!DOCTYPE svg PUBLIC |xmlns="http:\/\/www\.w3\.org\/2000\/svg")',
958 'group' => 'graphic',
960 'mime_type' => 'image/svg+xml',
961 'fail_id3' => 'ERROR',
962 'fail_ape' => 'ERROR',
966 // TIFF - still image - Tagged Information File Format (TIFF)
968 'pattern' => '^(II\x2A\x00|MM\x00\x2A)',
969 'group' => 'graphic',
971 'mime_type' => 'image/tiff',
972 'fail_id3' => 'ERROR',
973 'fail_ape' => 'ERROR',
977 // EFAX - still image - eFax (TIFF derivative)
979 'pattern' => '^\xDC\xFE',
980 'group' => 'graphic',
982 'mime_type' => 'image/efax',
983 'fail_id3' => 'ERROR',
984 'fail_ape' => 'ERROR',
990 // ISO - data - International Standards Organization (ISO) CD-ROM Image
992 'pattern' => '^.{32769}CD001',
995 'mime_type' => 'application/octet-stream',
996 'fail_id3' => 'ERROR',
997 'fail_ape' => 'ERROR',
998 'iconv_req' => false,
1001 // RAR - data - RAR compressed data
1003 'pattern' => '^Rar\!',
1004 'group' => 'archive',
1006 'mime_type' => 'application/octet-stream',
1007 'fail_id3' => 'ERROR',
1008 'fail_ape' => 'ERROR',
1011 // SZIP - audio/data - SZIP compressed data
1013 'pattern' => '^SZ\x0A\x04',
1014 'group' => 'archive',
1016 'mime_type' => 'application/octet-stream',
1017 'fail_id3' => 'ERROR',
1018 'fail_ape' => 'ERROR',
1021 // TAR - data - TAR compressed data
1023 'pattern' => '^.{100}[0-9\x20]{7}\x00[0-9\x20]{7}\x00[0-9\x20]{7}\x00[0-9\x20\x00]{12}[0-9\x20\x00]{12}',
1024 'group' => 'archive',
1026 'mime_type' => 'application/x-tar',
1027 'fail_id3' => 'ERROR',
1028 'fail_ape' => 'ERROR',
1031 // GZIP - data - GZIP compressed data
1033 'pattern' => '^\x1F\x8B\x08',
1034 'group' => 'archive',
1036 'mime_type' => 'application/x-gzip',
1037 'fail_id3' => 'ERROR',
1038 'fail_ape' => 'ERROR',
1041 // ZIP - data - ZIP compressed data
1043 'pattern' => '^PK\x03\x04',
1044 'group' => 'archive',
1046 'mime_type' => 'application/zip',
1047 'fail_id3' => 'ERROR',
1048 'fail_ape' => 'ERROR',
1052 // Misc other formats
1054 // PAR2 - data - Parity Volume Set Specification 2.0
1056 'pattern' => '^PAR2\x00PKT',
1059 'mime_type' => 'application/octet-stream',
1060 'fail_id3' => 'ERROR',
1061 'fail_ape' => 'ERROR',
1064 // PDF - data - Portable Document Format
1066 'pattern' => '^\x25PDF',
1069 'mime_type' => 'application/pdf',
1070 'fail_id3' => 'ERROR',
1071 'fail_ape' => 'ERROR',
1074 // MSOFFICE - data - ZIP compressed data
1075 'msoffice' => array(
1076 'pattern' => '^\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1', // D0CF11E == DOCFILE == Microsoft Office Document
1078 'module' => 'msoffice',
1079 'mime_type' => 'application/octet-stream',
1080 'fail_id3' => 'ERROR',
1081 'fail_ape' => 'ERROR',
1084 // CUE - data - CUEsheet (index to single-file disc images)
1086 'pattern' => '', // empty pattern means cannot be automatically detected, will fall through all other formats and match based on filename and very basic file contents
1089 'mime_type' => 'application/octet-stream',
1095 return $format_info;
1100 public function GetFileFormat(&$filedata, $filename='') {
1101 // this function will determine the format of a file based on usually
1102 // the first 2-4 bytes of the file (8 bytes for PNG, 16 bytes for JPG,
1103 // and in the case of ISO CD image, 6 bytes offset 32kb from the start
1106 // Identify file format - loop through $format_info and detect with reg expr
1107 foreach ($this->GetFileFormatArray() as $format_name => $info) {
1108 // The /s switch on preg_match() forces preg_match() NOT to treat
1109 // newline (0x0A) characters as special chars but do a binary match
1110 if (!empty($info['pattern']) && preg_match('#'.$info['pattern'].'#s', $filedata)) {
1111 $info['include'] = 'module.'.$info['group'].'.'.$info['module'].'.php';
1117 if (preg_match('#\.mp[123a]$#i', $filename)) {
1118 // Too many mp3 encoders on the market put gabage in front of mpeg files
1119 // use assume format on these if format detection failed
1120 $GetFileFormatArray = $this->GetFileFormatArray();
1121 $info = $GetFileFormatArray['mp3'];
1122 $info['include'] = 'module.'.$info['group'].'.'.$info['module'].'.php';
1124 } elseif (preg_match('/\.cue$/i', $filename) && preg_match('#FILE "[^"]+" (BINARY|MOTOROLA|AIFF|WAVE|MP3)#', $filedata)) {
1125 // there's not really a useful consistent "magic" at the beginning of .cue files to identify them
1126 // so until I think of something better, just go by filename if all other format checks fail
1127 // and verify there's at least one instance of "TRACK xx AUDIO" in the file
1128 $GetFileFormatArray = $this->GetFileFormatArray();
1129 $info = $GetFileFormatArray['cue'];
1130 $info['include'] = 'module.'.$info['group'].'.'.$info['module'].'.php';
1138 // converts array to $encoding charset from $this->encoding
1139 public function CharConvert(&$array, $encoding) {
1141 // identical encoding - end here
1142 if ($encoding == $this->encoding) {
1147 foreach ($array as $key => $value) {
1150 if (is_array($value)) {
1151 $this->CharConvert($array[$key], $encoding);
1155 elseif (is_string($value)) {
1156 $array[$key] = trim(getid3_lib::iconv_fallback($encoding, $this->encoding, $value));
1162 public function HandleAllTags() {
1164 // key name => array (tag name, character encoding)
1168 'asf' => array('asf' , 'UTF-16LE'),
1169 'midi' => array('midi' , 'ISO-8859-1'),
1170 'nsv' => array('nsv' , 'ISO-8859-1'),
1171 'ogg' => array('vorbiscomment' , 'UTF-8'),
1172 'png' => array('png' , 'UTF-8'),
1173 'tiff' => array('tiff' , 'ISO-8859-1'),
1174 'quicktime' => array('quicktime' , 'UTF-8'),
1175 'real' => array('real' , 'ISO-8859-1'),
1176 'vqf' => array('vqf' , 'ISO-8859-1'),
1177 'zip' => array('zip' , 'ISO-8859-1'),
1178 'riff' => array('riff' , 'ISO-8859-1'),
1179 'lyrics3' => array('lyrics3' , 'ISO-8859-1'),
1180 'id3v1' => array('id3v1' , $this->encoding_id3v1),
1181 'id3v2' => array('id3v2' , 'UTF-8'), // not according to the specs (every frame can have a different encoding), but getID3() force-converts all encodings to UTF-8
1182 'ape' => array('ape' , 'UTF-8'),
1183 'cue' => array('cue' , 'ISO-8859-1'),
1184 'matroska' => array('matroska' , 'UTF-8'),
1185 'flac' => array('vorbiscomment' , 'UTF-8'),
1186 'divxtag' => array('divx' , 'ISO-8859-1'),
1187 'iptc' => array('iptc' , 'ISO-8859-1'),
1191 // loop through comments array
1192 foreach ($tags as $comment_name => $tagname_encoding_array) {
1193 list($tag_name, $encoding) = $tagname_encoding_array;
1195 // fill in default encoding type if not already present
1196 if (isset($this->info[$comment_name]) && !isset($this->info[$comment_name]['encoding'])) {
1197 $this->info[$comment_name]['encoding'] = $encoding;
1200 // copy comments if key name set
1201 if (!empty($this->info[$comment_name]['comments'])) {
1202 foreach ($this->info[$comment_name]['comments'] as $tag_key => $valuearray) {
1203 foreach ($valuearray as $key => $value) {
1204 if (is_string($value)) {
1205 $value = trim($value, " \r\n\t"); // do not trim nulls from $value!! Unicode characters will get mangled if trailing nulls are removed!
1208 if (!is_numeric($key)) {
1209 $this->info['tags'][trim($tag_name)][trim($tag_key)][$key] = $value;
1211 $this->info['tags'][trim($tag_name)][trim($tag_key)][] = $value;
1215 if ($tag_key == 'picture') {
1216 unset($this->info[$comment_name]['comments'][$tag_key]);
1220 if (!isset($this->info['tags'][$tag_name])) {
1221 // comments are set but contain nothing but empty strings, so skip
1225 if ($this->option_tags_html) {
1226 foreach ($this->info['tags'][$tag_name] as $tag_key => $valuearray) {
1227 $this->info['tags_html'][$tag_name][$tag_key] = getid3_lib::recursiveMultiByteCharString2HTML($valuearray, $encoding);
1231 $this->CharConvert($this->info['tags'][$tag_name], $encoding); // only copy gets converted!
1236 // pictures can take up a lot of space, and we don't need multiple copies of them
1237 // let there be a single copy in [comments][picture], and not elsewhere
1238 if (!empty($this->info['tags'])) {
1239 $unset_keys = array('tags', 'tags_html');
1240 foreach ($this->info['tags'] as $tagtype => $tagarray) {
1241 foreach ($tagarray as $tagname => $tagdata) {
1242 if ($tagname == 'picture') {
1243 foreach ($tagdata as $key => $tagarray) {
1244 $this->info['comments']['picture'][] = $tagarray;
1245 if (isset($tagarray['data']) && isset($tagarray['image_mime'])) {
1246 if (isset($this->info['tags'][$tagtype][$tagname][$key])) {
1247 unset($this->info['tags'][$tagtype][$tagname][$key]);
1249 if (isset($this->info['tags_html'][$tagtype][$tagname][$key])) {
1250 unset($this->info['tags_html'][$tagtype][$tagname][$key]);
1256 foreach ($unset_keys as $unset_key) {
1257 // remove possible empty keys from (e.g. [tags][id3v2][picture])
1258 if (empty($this->info[$unset_key][$tagtype]['picture'])) {
1259 unset($this->info[$unset_key][$tagtype]['picture']);
1261 if (empty($this->info[$unset_key][$tagtype])) {
1262 unset($this->info[$unset_key][$tagtype]);
1264 if (empty($this->info[$unset_key])) {
1265 unset($this->info[$unset_key]);
1268 // remove duplicate copy of picture data from (e.g. [id3v2][comments][picture])
1269 if (isset($this->info[$tagtype]['comments']['picture'])) {
1270 unset($this->info[$tagtype]['comments']['picture']);
1272 if (empty($this->info[$tagtype]['comments'])) {
1273 unset($this->info[$tagtype]['comments']);
1275 if (empty($this->info[$tagtype])) {
1276 unset($this->info[$tagtype]);
1283 public function getHashdata($algorithm) {
1284 switch ($algorithm) {
1290 return $this->error('bad algorithm "'.$algorithm.'" in getHashdata()');
1294 if (!empty($this->info['fileformat']) && !empty($this->info['dataformat']) && ($this->info['fileformat'] == 'ogg') && ($this->info['audio']['dataformat'] == 'vorbis')) {
1296 // We cannot get an identical md5_data value for Ogg files where the comments
1297 // span more than 1 Ogg page (compared to the same audio data with smaller
1298 // comments) using the normal getID3() method of MD5'ing the data between the
1299 // end of the comments and the end of the file (minus any trailing tags),
1300 // because the page sequence numbers of the pages that the audio data is on
1301 // do not match. Under normal circumstances, where comments are smaller than
1302 // the nominal 4-8kB page size, then this is not a problem, but if there are
1303 // very large comments, the only way around it is to strip off the comment
1304 // tags with vorbiscomment and MD5 that file.
1305 // This procedure must be applied to ALL Ogg files, not just the ones with
1306 // comments larger than 1 page, because the below method simply MD5's the
1307 // whole file with the comments stripped, not just the portion after the
1308 // comments block (which is the standard getID3() method.
1310 // The above-mentioned problem of comments spanning multiple pages and changing
1311 // page sequence numbers likely happens for OggSpeex and OggFLAC as well, but
1312 // currently vorbiscomment only works on OggVorbis files.
1314 if (preg_match('#(1|ON)#i', ini_get('safe_mode'))) {
1316 $this->warning('Failed making system call to vorbiscomment.exe - '.$algorithm.'_data is incorrect - error returned: PHP running in Safe Mode (backtick operator not available)');
1317 $this->info[$algorithm.'_data'] = false;
1321 // Prevent user from aborting script
1322 $old_abort = ignore_user_abort(true);
1324 // Create empty file
1325 $empty = tempnam(GETID3_TEMP_DIR, 'getID3');
1328 // Use vorbiscomment to make temp file without comments
1329 $temp = tempnam(GETID3_TEMP_DIR, 'getID3');
1330 $file = $this->info['filenamepath'];
1332 if (GETID3_OS_ISWINDOWS) {
1334 if (file_exists(GETID3_HELPERAPPSDIR.'vorbiscomment.exe')) {
1336 $commandline = '"'.GETID3_HELPERAPPSDIR.'vorbiscomment.exe" -w -c "'.$empty.'" "'.$file.'" "'.$temp.'"';
1337 $VorbisCommentError = `$commandline`;
1341 $VorbisCommentError = 'vorbiscomment.exe not found in '.GETID3_HELPERAPPSDIR;
1347 $commandline = 'vorbiscomment -w -c "'.$empty.'" "'.$file.'" "'.$temp.'" 2>&1';
1348 $commandline = 'vorbiscomment -w -c '.escapeshellarg($empty).' '.escapeshellarg($file).' '.escapeshellarg($temp).' 2>&1';
1349 $VorbisCommentError = `$commandline`;
1353 if (!empty($VorbisCommentError)) {
1355 $this->info['warning'][] = 'Failed making system call to vorbiscomment(.exe) - '.$algorithm.'_data will be incorrect. If vorbiscomment is unavailable, please download from http://www.vorbis.com/download.psp and put in the getID3() directory. Error returned: '.$VorbisCommentError;
1356 $this->info[$algorithm.'_data'] = false;
1360 // Get hash of newly created file
1361 switch ($algorithm) {
1363 $this->info[$algorithm.'_data'] = md5_file($temp);
1367 $this->info[$algorithm.'_data'] = sha1_file($temp);
1376 // Reset abort setting
1377 ignore_user_abort($old_abort);
1383 if (!empty($this->info['avdataoffset']) || (isset($this->info['avdataend']) && ($this->info['avdataend'] < $this->info['filesize']))) {
1385 // get hash from part of file
1386 $this->info[$algorithm.'_data'] = getid3_lib::hash_data($this->info['filenamepath'], $this->info['avdataoffset'], $this->info['avdataend'], $algorithm);
1390 // get hash from whole file
1391 switch ($algorithm) {
1393 $this->info[$algorithm.'_data'] = md5_file($this->info['filenamepath']);
1397 $this->info[$algorithm.'_data'] = sha1_file($this->info['filenamepath']);
1407 public function ChannelsBitratePlaytimeCalculations() {
1409 // set channelmode on audio
1410 if (!empty($this->info['audio']['channelmode']) || !isset($this->info['audio']['channels'])) {
1412 } elseif ($this->info['audio']['channels'] == 1) {
1413 $this->info['audio']['channelmode'] = 'mono';
1414 } elseif ($this->info['audio']['channels'] == 2) {
1415 $this->info['audio']['channelmode'] = 'stereo';
1418 // Calculate combined bitrate - audio + video
1419 $CombinedBitrate = 0;
1420 $CombinedBitrate += (isset($this->info['audio']['bitrate']) ? $this->info['audio']['bitrate'] : 0);
1421 $CombinedBitrate += (isset($this->info['video']['bitrate']) ? $this->info['video']['bitrate'] : 0);
1422 if (($CombinedBitrate > 0) && empty($this->info['bitrate'])) {
1423 $this->info['bitrate'] = $CombinedBitrate;
1425 //if ((isset($this->info['video']) && !isset($this->info['video']['bitrate'])) || (isset($this->info['audio']) && !isset($this->info['audio']['bitrate']))) {
1426 // // for example, VBR MPEG video files cannot determine video bitrate:
1427 // // should not set overall bitrate and playtime from audio bitrate only
1428 // unset($this->info['bitrate']);
1431 // video bitrate undetermined, but calculable
1432 if (isset($this->info['video']['dataformat']) && $this->info['video']['dataformat'] && (!isset($this->info['video']['bitrate']) || ($this->info['video']['bitrate'] == 0))) {
1433 // if video bitrate not set
1434 if (isset($this->info['audio']['bitrate']) && ($this->info['audio']['bitrate'] > 0) && ($this->info['audio']['bitrate'] == $this->info['bitrate'])) {
1435 // AND if audio bitrate is set to same as overall bitrate
1436 if (isset($this->info['playtime_seconds']) && ($this->info['playtime_seconds'] > 0)) {
1437 // AND if playtime is set
1438 if (isset($this->info['avdataend']) && isset($this->info['avdataoffset'])) {
1439 // AND if AV data offset start/end is known
1440 // THEN we can calculate the video bitrate
1441 $this->info['bitrate'] = round((($this->info['avdataend'] - $this->info['avdataoffset']) * 8) / $this->info['playtime_seconds']);
1442 $this->info['video']['bitrate'] = $this->info['bitrate'] - $this->info['audio']['bitrate'];
1448 if ((!isset($this->info['playtime_seconds']) || ($this->info['playtime_seconds'] <= 0)) && !empty($this->info['bitrate'])) {
1449 $this->info['playtime_seconds'] = (($this->info['avdataend'] - $this->info['avdataoffset']) * 8) / $this->info['bitrate'];
1452 if (!isset($this->info['bitrate']) && !empty($this->info['playtime_seconds'])) {
1453 $this->info['bitrate'] = (($this->info['avdataend'] - $this->info['avdataoffset']) * 8) / $this->info['playtime_seconds'];
1455 if (isset($this->info['bitrate']) && empty($this->info['audio']['bitrate']) && empty($this->info['video']['bitrate'])) {
1456 if (isset($this->info['audio']['dataformat']) && empty($this->info['video']['resolution_x'])) {
1458 $this->info['audio']['bitrate'] = $this->info['bitrate'];
1459 } elseif (isset($this->info['video']['resolution_x']) && empty($this->info['audio']['dataformat'])) {
1461 $this->info['video']['bitrate'] = $this->info['bitrate'];
1465 // Set playtime string
1466 if (!empty($this->info['playtime_seconds']) && empty($this->info['playtime_string'])) {
1467 $this->info['playtime_string'] = getid3_lib::PlaytimeString($this->info['playtime_seconds']);
1472 public function CalculateCompressionRatioVideo() {
1473 if (empty($this->info['video'])) {
1476 if (empty($this->info['video']['resolution_x']) || empty($this->info['video']['resolution_y'])) {
1479 if (empty($this->info['video']['bits_per_sample'])) {
1483 switch ($this->info['video']['dataformat']) {
1491 $PlaytimeSeconds = 1;
1492 $BitrateCompressed = $this->info['filesize'] * 8;
1496 if (!empty($this->info['video']['frame_rate'])) {
1497 $FrameRate = $this->info['video']['frame_rate'];
1501 if (!empty($this->info['playtime_seconds'])) {
1502 $PlaytimeSeconds = $this->info['playtime_seconds'];
1506 if (!empty($this->info['video']['bitrate'])) {
1507 $BitrateCompressed = $this->info['video']['bitrate'];
1513 $BitrateUncompressed = $this->info['video']['resolution_x'] * $this->info['video']['resolution_y'] * $this->info['video']['bits_per_sample'] * $FrameRate;
1515 $this->info['video']['compression_ratio'] = $BitrateCompressed / $BitrateUncompressed;
1520 public function CalculateCompressionRatioAudio() {
1521 if (empty($this->info['audio']['bitrate']) || empty($this->info['audio']['channels']) || empty($this->info['audio']['sample_rate']) || !is_numeric($this->info['audio']['sample_rate'])) {
1524 $this->info['audio']['compression_ratio'] = $this->info['audio']['bitrate'] / ($this->info['audio']['channels'] * $this->info['audio']['sample_rate'] * (!empty($this->info['audio']['bits_per_sample']) ? $this->info['audio']['bits_per_sample'] : 16));
1526 if (!empty($this->info['audio']['streams'])) {
1527 foreach ($this->info['audio']['streams'] as $streamnumber => $streamdata) {
1528 if (!empty($streamdata['bitrate']) && !empty($streamdata['channels']) && !empty($streamdata['sample_rate'])) {
1529 $this->info['audio']['streams'][$streamnumber]['compression_ratio'] = $streamdata['bitrate'] / ($streamdata['channels'] * $streamdata['sample_rate'] * (!empty($streamdata['bits_per_sample']) ? $streamdata['bits_per_sample'] : 16));
1537 public function CalculateReplayGain() {
1538 if (isset($this->info['replay_gain'])) {
1539 if (!isset($this->info['replay_gain']['reference_volume'])) {
1540 $this->info['replay_gain']['reference_volume'] = (double) 89.0;
1542 if (isset($this->info['replay_gain']['track']['adjustment'])) {
1543 $this->info['replay_gain']['track']['volume'] = $this->info['replay_gain']['reference_volume'] - $this->info['replay_gain']['track']['adjustment'];
1545 if (isset($this->info['replay_gain']['album']['adjustment'])) {
1546 $this->info['replay_gain']['album']['volume'] = $this->info['replay_gain']['reference_volume'] - $this->info['replay_gain']['album']['adjustment'];
1549 if (isset($this->info['replay_gain']['track']['peak'])) {
1550 $this->info['replay_gain']['track']['max_noclip_gain'] = 0 - getid3_lib::RGADamplitude2dB($this->info['replay_gain']['track']['peak']);
1552 if (isset($this->info['replay_gain']['album']['peak'])) {
1553 $this->info['replay_gain']['album']['max_noclip_gain'] = 0 - getid3_lib::RGADamplitude2dB($this->info['replay_gain']['album']['peak']);
1559 public function ProcessAudioStreams() {
1560 if (!empty($this->info['audio']['bitrate']) || !empty($this->info['audio']['channels']) || !empty($this->info['audio']['sample_rate'])) {
1561 if (!isset($this->info['audio']['streams'])) {
1562 foreach ($this->info['audio'] as $key => $value) {
1563 if ($key != 'streams') {
1564 $this->info['audio']['streams'][0][$key] = $value;
1572 public function getid3_tempnam() {
1573 return tempnam($this->tempdir, 'gI3');
1576 public function include_module($name) {
1577 //if (!file_exists($this->include_path.'module.'.$name.'.php')) {
1578 if (!file_exists(GETID3_INCLUDEPATH.'module.'.$name.'.php')) {
1579 throw new getid3_exception('Required module.'.$name.'.php is missing.');
1581 include_once(GETID3_INCLUDEPATH.'module.'.$name.'.php');
1588 abstract class getid3_handler {
1593 protected $getid3; // pointer
1595 protected $data_string_flag = false; // analyzing filepointer or string
1596 protected $data_string = ''; // string to analyze
1597 protected $data_string_position = 0; // seek position in string
1598 protected $data_string_length = 0; // string length
1600 private $dependency_to = null;
1603 public function __construct(getID3 $getid3, $call_module=null) {
1604 $this->getid3 = $getid3;
1607 $this->dependency_to = str_replace('getid3_', '', $call_module);
1612 // Analyze from file pointer
1613 abstract public function Analyze();
1616 // Analyze from string instead
1617 public function AnalyzeString($string) {
1618 // Enter string mode
1619 $this->setStringMode($string);
1622 $saved_avdataoffset = $this->getid3->info['avdataoffset'];
1623 $saved_avdataend = $this->getid3->info['avdataend'];
1624 $saved_filesize = (isset($this->getid3->info['filesize']) ? $this->getid3->info['filesize'] : null); // may be not set if called as dependency without openfile() call
1627 $this->getid3->info['avdataoffset'] = 0;
1628 $this->getid3->info['avdataend'] = $this->getid3->info['filesize'] = $this->data_string_length;
1633 // Restore some info
1634 $this->getid3->info['avdataoffset'] = $saved_avdataoffset;
1635 $this->getid3->info['avdataend'] = $saved_avdataend;
1636 $this->getid3->info['filesize'] = $saved_filesize;
1639 $this->data_string_flag = false;
1642 public function setStringMode($string) {
1643 $this->data_string_flag = true;
1644 $this->data_string = $string;
1645 $this->data_string_length = strlen($string);
1648 protected function ftell() {
1649 if ($this->data_string_flag) {
1650 return $this->data_string_position;
1652 return ftell($this->getid3->fp);
1655 protected function fread($bytes) {
1656 if ($this->data_string_flag) {
1657 $this->data_string_position += $bytes;
1658 return substr($this->data_string, $this->data_string_position - $bytes, $bytes);
1660 $pos = $this->ftell() + $bytes;
1661 if (!getid3_lib::intValueSupported($pos)) {
1662 throw new getid3_exception('cannot fread('.$bytes.' from '.$this->ftell().') because beyond PHP filesystem limit', 10);
1664 return fread($this->getid3->fp, $bytes);
1667 protected function fseek($bytes, $whence=SEEK_SET) {
1668 if ($this->data_string_flag) {
1671 $this->data_string_position = $bytes;
1675 $this->data_string_position += $bytes;
1679 $this->data_string_position = $this->data_string_length + $bytes;
1685 if ($whence == SEEK_CUR) {
1686 $pos = $this->ftell() + $bytes;
1687 } elseif ($whence == SEEK_END) {
1688 $pos = $this->getid3->info['filesize'] + $bytes;
1690 if (!getid3_lib::intValueSupported($pos)) {
1691 throw new getid3_exception('cannot fseek('.$pos.') because beyond PHP filesystem limit', 10);
1694 return fseek($this->getid3->fp, $bytes, $whence);
1697 protected function feof() {
1698 if ($this->data_string_flag) {
1699 return $this->data_string_position >= $this->data_string_length;
1701 return feof($this->getid3->fp);
1704 final protected function isDependencyFor($module) {
1705 return $this->dependency_to == $module;
1708 protected function error($text) {
1709 $this->getid3->info['error'][] = $text;
1714 protected function warning($text) {
1715 return $this->getid3->warning($text);
1718 protected function notice($text) {
1719 // does nothing for now
1722 public function saveAttachment($name, $offset, $length, $image_mime=null) {
1725 // do not extract at all
1726 if ($this->getid3->option_save_attachments === getID3::ATTACHMENTS_NONE) {
1728 $attachment = null; // do not set any
1730 // extract to return array
1731 } elseif ($this->getid3->option_save_attachments === getID3::ATTACHMENTS_INLINE) {
1733 $this->fseek($offset);
1734 $attachment = $this->fread($length); // get whole data in one pass, till it is anyway stored in memory
1735 if ($attachment === false || strlen($attachment) != $length) {
1736 throw new Exception('failed to read attachment data');
1739 // assume directory path is given
1742 // set up destination path
1743 $dir = rtrim(str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $this->getid3->option_save_attachments), DIRECTORY_SEPARATOR);
1744 if (!is_dir($dir) || !is_writable($dir)) { // check supplied directory
1745 throw new Exception('supplied path ('.$dir.') does not exist, or is not writable');
1747 $dest = $dir.DIRECTORY_SEPARATOR.$name.($image_mime ? '.'.getid3_lib::ImageExtFromMime($image_mime) : '');
1750 if (($fp_dest = fopen($dest, 'wb')) == false) {
1751 throw new Exception('failed to create file '.$dest);
1755 $this->fseek($offset);
1756 $buffersize = ($this->data_string_flag ? $length : $this->getid3->fread_buffer_size());
1757 $bytesleft = $length;
1758 while ($bytesleft > 0) {
1759 if (($buffer = $this->fread(min($buffersize, $bytesleft))) === false || ($byteswritten = fwrite($fp_dest, $buffer)) === false || ($byteswritten === 0)) {
1760 throw new Exception($buffer === false ? 'not enough data to read' : 'failed to write to destination file, may be not enough disk space');
1762 $bytesleft -= $byteswritten;
1766 $attachment = $dest;
1770 } catch (Exception $e) {
1772 // close and remove dest file if created
1773 if (isset($fp_dest) && is_resource($fp_dest)) {
1778 // do not set any is case of error
1780 $this->warning('Failed to extract attachment '.$name.': '.$e->getMessage());
1784 // seek to the end of attachment
1785 $this->fseek($offset + $length);
1793 class getid3_exception extends Exception