1<?php
2
3/////////////////////////////////////////////////////////////////
4/// getID3() by James Heinrich <info@getid3.org>               //
5//  available at https://github.com/JamesHeinrich/getID3       //
6//            or https://www.getid3.org                        //
7//            or http://getid3.sourceforge.net                 //
8//  see readme.txt for more details                            //
9/////////////////////////////////////////////////////////////////
10//                                                             //
11// module.audio.mpc.php                                        //
12// module for analyzing Musepack/MPEG+ Audio files             //
13// dependencies: NONE                                          //
14//                                                            ///
15/////////////////////////////////////////////////////////////////
16
17if (!defined('GETID3_INCLUDEPATH')) { // prevent path-exposing attacks that access modules directly on public webservers
18	exit;
19}
20
21class getid3_mpc extends getid3_handler
22{
23	/**
24	 * @return bool
25	 */
26	public function Analyze() {
27		$info = &$this->getid3->info;
28
29		$info['mpc']['header'] = array();
30		$thisfile_mpc_header   = &$info['mpc']['header'];
31
32		$info['fileformat']               = 'mpc';
33		$info['audio']['dataformat']      = 'mpc';
34		$info['audio']['bitrate_mode']    = 'vbr';
35		$info['audio']['channels']        = 2;  // up to SV7 the format appears to have been hardcoded for stereo only
36		$info['audio']['lossless']        = false;
37
38		$this->fseek($info['avdataoffset']);
39		$MPCheaderData = $this->fread(4);
40		$info['mpc']['header']['preamble'] = substr($MPCheaderData, 0, 4); // should be 'MPCK' (SV8) or 'MP+' (SV7), otherwise possible stream data (SV4-SV6)
41		if (preg_match('#^MPCK#', $info['mpc']['header']['preamble'])) {
42
43			// this is SV8
44			return $this->ParseMPCsv8();
45
46		} elseif (preg_match('#^MP\+#', $info['mpc']['header']['preamble'])) {
47
48			// this is SV7
49			return $this->ParseMPCsv7();
50
51		} elseif (preg_match('/^[\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]/s', $MPCheaderData)) {
52
53			// this is SV4 - SV6, handle seperately
54			return $this->ParseMPCsv6();
55
56		} else {
57
58			$this->error('Expecting "MP+" or "MPCK" at offset '.$info['avdataoffset'].', found "'.getid3_lib::PrintHexBytes(substr($MPCheaderData, 0, 4)).'"');
59			unset($info['fileformat']);
60			unset($info['mpc']);
61			return false;
62
63		}
64	}
65
66	/**
67	 * @return bool
68	 */
69	public function ParseMPCsv8() {
70		// this is SV8
71		// http://trac.musepack.net/trac/wiki/SV8Specification
72
73		$info = &$this->getid3->info;
74		$thisfile_mpc_header = &$info['mpc']['header'];
75
76		$keyNameSize            = 2;
77		$maxHandledPacketLength = 9; // specs say: "n*8; 0 < n < 10"
78
79		$offset = $this->ftell();
80		while ($offset < $info['avdataend']) {
81			$thisPacket = array();
82			$thisPacket['offset'] = $offset;
83			$packet_offset = 0;
84
85			// Size is a variable-size field, could be 1-4 bytes (possibly more?)
86			// read enough data in and figure out the exact size later
87			$MPCheaderData = $this->fread($keyNameSize + $maxHandledPacketLength);
88			$packet_offset += $keyNameSize;
89			$thisPacket['key']      = substr($MPCheaderData, 0, $keyNameSize);
90			$thisPacket['key_name'] = $this->MPCsv8PacketName($thisPacket['key']);
91			if ($thisPacket['key'] == $thisPacket['key_name']) {
92				$this->error('Found unexpected key value "'.$thisPacket['key'].'" at offset '.$thisPacket['offset']);
93				return false;
94			}
95			$packetLength = 0;
96			$thisPacket['packet_size'] = $this->SV8variableLengthInteger(substr($MPCheaderData, $keyNameSize), $packetLength); // includes keyname and packet_size field
97			if ($thisPacket['packet_size'] === false) {
98				$this->error('Did not find expected packet length within '.$maxHandledPacketLength.' bytes at offset '.($thisPacket['offset'] + $keyNameSize));
99				return false;
100			}
101			$packet_offset += $packetLength;
102			$offset += $thisPacket['packet_size'];
103
104			switch ($thisPacket['key']) {
105				case 'SH': // Stream Header
106					$moreBytesToRead = $thisPacket['packet_size'] - $keyNameSize - $maxHandledPacketLength;
107					if ($moreBytesToRead > 0) {
108						$MPCheaderData .= $this->fread($moreBytesToRead);
109					}
110					$thisPacket['crc']               =       getid3_lib::BigEndian2Int(substr($MPCheaderData, $packet_offset, 4));
111					$packet_offset += 4;
112					$thisPacket['stream_version']    =       getid3_lib::BigEndian2Int(substr($MPCheaderData, $packet_offset, 1));
113					$packet_offset += 1;
114
115					$packetLength = 0;
116					$thisPacket['sample_count']      = $this->SV8variableLengthInteger(substr($MPCheaderData, $packet_offset, $maxHandledPacketLength), $packetLength);
117					$packet_offset += $packetLength;
118
119					$packetLength = 0;
120					$thisPacket['beginning_silence'] = $this->SV8variableLengthInteger(substr($MPCheaderData, $packet_offset, $maxHandledPacketLength), $packetLength);
121					$packet_offset += $packetLength;
122
123					$otherUsefulData                 =       getid3_lib::BigEndian2Int(substr($MPCheaderData, $packet_offset, 2));
124					$packet_offset += 2;
125					$thisPacket['sample_frequency_raw'] =        (($otherUsefulData & 0xE000) >> 13);
126					$thisPacket['max_bands_used']       =        (($otherUsefulData & 0x1F00) >>  8);
127					$thisPacket['channels']             =        (($otherUsefulData & 0x00F0) >>  4) + 1;
128					$thisPacket['ms_used']              = (bool) (($otherUsefulData & 0x0008) >>  3);
129					$thisPacket['audio_block_frames']   =        (($otherUsefulData & 0x0007) >>  0);
130					$thisPacket['sample_frequency']     = $this->MPCfrequencyLookup($thisPacket['sample_frequency_raw']);
131
132					$thisfile_mpc_header['mid_side_stereo']      = $thisPacket['ms_used'];
133					$thisfile_mpc_header['sample_rate']          = $thisPacket['sample_frequency'];
134					$thisfile_mpc_header['samples']              = $thisPacket['sample_count'];
135					$thisfile_mpc_header['stream_version_major'] = $thisPacket['stream_version'];
136
137					$info['audio']['channels']    = $thisPacket['channels'];
138					$info['audio']['sample_rate'] = $thisPacket['sample_frequency'];
139					$info['playtime_seconds'] = $thisPacket['sample_count'] / $thisPacket['sample_frequency'];
140					$info['audio']['bitrate'] = (($info['avdataend'] - $info['avdataoffset']) * 8) / $info['playtime_seconds'];
141					break;
142
143				case 'RG': // Replay Gain
144					$moreBytesToRead = $thisPacket['packet_size'] - $keyNameSize - $maxHandledPacketLength;
145					if ($moreBytesToRead > 0) {
146						$MPCheaderData .= $this->fread($moreBytesToRead);
147					}
148					$thisPacket['replaygain_version']     =       getid3_lib::BigEndian2Int(substr($MPCheaderData, $packet_offset, 1));
149					$packet_offset += 1;
150					$thisPacket['replaygain_title_gain']  =       getid3_lib::BigEndian2Int(substr($MPCheaderData, $packet_offset, 2));
151					$packet_offset += 2;
152					$thisPacket['replaygain_title_peak']  =       getid3_lib::BigEndian2Int(substr($MPCheaderData, $packet_offset, 2));
153					$packet_offset += 2;
154					$thisPacket['replaygain_album_gain']  =       getid3_lib::BigEndian2Int(substr($MPCheaderData, $packet_offset, 2));
155					$packet_offset += 2;
156					$thisPacket['replaygain_album_peak']  =       getid3_lib::BigEndian2Int(substr($MPCheaderData, $packet_offset, 2));
157					$packet_offset += 2;
158
159					if ($thisPacket['replaygain_title_gain']) { $info['replay_gain']['title']['gain'] = $thisPacket['replaygain_title_gain']; }
160					if ($thisPacket['replaygain_title_peak']) { $info['replay_gain']['title']['peak'] = $thisPacket['replaygain_title_peak']; }
161					if ($thisPacket['replaygain_album_gain']) { $info['replay_gain']['album']['gain'] = $thisPacket['replaygain_album_gain']; }
162					if ($thisPacket['replaygain_album_peak']) { $info['replay_gain']['album']['peak'] = $thisPacket['replaygain_album_peak']; }
163					break;
164
165				case 'EI': // Encoder Info
166					$moreBytesToRead = $thisPacket['packet_size'] - $keyNameSize - $maxHandledPacketLength;
167					if ($moreBytesToRead > 0) {
168						$MPCheaderData .= $this->fread($moreBytesToRead);
169					}
170					$profile_pns                 = getid3_lib::BigEndian2Int(substr($MPCheaderData, $packet_offset, 1));
171					$packet_offset += 1;
172					$quality_int =                   (($profile_pns & 0xF0) >> 4);
173					$quality_dec =                   (($profile_pns & 0x0E) >> 3);
174					$thisPacket['quality'] = (float) $quality_int + ($quality_dec / 8);
175					$thisPacket['pns_tool'] = (bool) (($profile_pns & 0x01) >> 0);
176					$thisPacket['version_major'] = getid3_lib::BigEndian2Int(substr($MPCheaderData, $packet_offset, 1));
177					$packet_offset += 1;
178					$thisPacket['version_minor'] = getid3_lib::BigEndian2Int(substr($MPCheaderData, $packet_offset, 1));
179					$packet_offset += 1;
180					$thisPacket['version_build'] = getid3_lib::BigEndian2Int(substr($MPCheaderData, $packet_offset, 1));
181					$packet_offset += 1;
182					$thisPacket['version'] = $thisPacket['version_major'].'.'.$thisPacket['version_minor'].'.'.$thisPacket['version_build'];
183
184					$info['audio']['encoder'] = 'MPC v'.$thisPacket['version'].' ('.(($thisPacket['version_minor'] % 2) ? 'unstable' : 'stable').')';
185					$thisfile_mpc_header['encoder_version'] = $info['audio']['encoder'];
186					//$thisfile_mpc_header['quality']         = (float) ($thisPacket['quality'] / 1.5875); // values can range from 0.000 to 15.875, mapped to qualities of 0.0 to 10.0
187					$thisfile_mpc_header['quality']         = (float) ($thisPacket['quality'] - 5); // values can range from 0.000 to 15.875, of which 0..4 are "reserved/experimental", and 5..15 are mapped to qualities of 0.0 to 10.0
188					break;
189
190				case 'SO': // Seek Table Offset
191					$packetLength = 0;
192					$thisPacket['seek_table_offset'] = $thisPacket['offset'] + $this->SV8variableLengthInteger(substr($MPCheaderData, $packet_offset, $maxHandledPacketLength), $packetLength);
193					$packet_offset += $packetLength;
194					break;
195
196				case 'ST': // Seek Table
197				case 'SE': // Stream End
198				case 'AP': // Audio Data
199					// nothing useful here, just skip this packet
200					$thisPacket = array();
201					break;
202
203				default:
204					$this->error('Found unhandled key type "'.$thisPacket['key'].'" at offset '.$thisPacket['offset']);
205					return false;
206			}
207			if (!empty($thisPacket)) {
208				$info['mpc']['packets'][] = $thisPacket;
209			}
210			$this->fseek($offset);
211		}
212		$thisfile_mpc_header['size'] = $offset;
213		return true;
214	}
215
216	/**
217	 * @return bool
218	 */
219	public function ParseMPCsv7() {
220		// this is SV7
221		// http://www.uni-jena.de/~pfk/mpp/sv8/header.html
222
223		$info = &$this->getid3->info;
224		$thisfile_mpc_header = &$info['mpc']['header'];
225		$offset = 0;
226
227		$thisfile_mpc_header['size'] = 28;
228		$MPCheaderData  = $info['mpc']['header']['preamble'];
229		$MPCheaderData .= $this->fread($thisfile_mpc_header['size'] - strlen($info['mpc']['header']['preamble']));
230		$offset = strlen('MP+');
231
232		$StreamVersionByte                           = getid3_lib::LittleEndian2Int(substr($MPCheaderData, $offset, 1));
233		$offset += 1;
234		$thisfile_mpc_header['stream_version_major'] = ($StreamVersionByte & 0x0F) >> 0;
235		$thisfile_mpc_header['stream_version_minor'] = ($StreamVersionByte & 0xF0) >> 4; // should always be 0, subversions no longer exist in SV8
236		$thisfile_mpc_header['frame_count']          = getid3_lib::LittleEndian2Int(substr($MPCheaderData, $offset, 4));
237		$offset += 4;
238
239		if ($thisfile_mpc_header['stream_version_major'] != 7) {
240			$this->error('Only Musepack SV7 supported (this file claims to be v'.$thisfile_mpc_header['stream_version_major'].')');
241			return false;
242		}
243
244		$FlagsDWORD1                                   = getid3_lib::LittleEndian2Int(substr($MPCheaderData, $offset, 4));
245		$offset += 4;
246		$thisfile_mpc_header['intensity_stereo']       = (bool) (($FlagsDWORD1 & 0x80000000) >> 31);
247		$thisfile_mpc_header['mid_side_stereo']        = (bool) (($FlagsDWORD1 & 0x40000000) >> 30);
248		$thisfile_mpc_header['max_subband']            =         ($FlagsDWORD1 & 0x3F000000) >> 24;
249		$thisfile_mpc_header['raw']['profile']         =         ($FlagsDWORD1 & 0x00F00000) >> 20;
250		$thisfile_mpc_header['begin_loud']             = (bool) (($FlagsDWORD1 & 0x00080000) >> 19);
251		$thisfile_mpc_header['end_loud']               = (bool) (($FlagsDWORD1 & 0x00040000) >> 18);
252		$thisfile_mpc_header['raw']['sample_rate']     =         ($FlagsDWORD1 & 0x00030000) >> 16;
253		$thisfile_mpc_header['max_level']              =         ($FlagsDWORD1 & 0x0000FFFF);
254
255		$thisfile_mpc_header['raw']['title_peak']      = getid3_lib::LittleEndian2Int(substr($MPCheaderData, $offset, 2));
256		$offset += 2;
257		$thisfile_mpc_header['raw']['title_gain']      = getid3_lib::LittleEndian2Int(substr($MPCheaderData, $offset, 2), true);
258		$offset += 2;
259
260		$thisfile_mpc_header['raw']['album_peak']      = getid3_lib::LittleEndian2Int(substr($MPCheaderData, $offset, 2));
261		$offset += 2;
262		$thisfile_mpc_header['raw']['album_gain']      = getid3_lib::LittleEndian2Int(substr($MPCheaderData, $offset, 2), true);
263		$offset += 2;
264
265		$FlagsDWORD2                                   = getid3_lib::LittleEndian2Int(substr($MPCheaderData, $offset, 4));
266		$offset += 4;
267		$thisfile_mpc_header['true_gapless']           = (bool) (($FlagsDWORD2 & 0x80000000) >> 31);
268		$thisfile_mpc_header['last_frame_length']      =         ($FlagsDWORD2 & 0x7FF00000) >> 20;
269
270
271		$thisfile_mpc_header['raw']['not_sure_what']   = getid3_lib::LittleEndian2Int(substr($MPCheaderData, $offset, 3));
272		$offset += 3;
273		$thisfile_mpc_header['raw']['encoder_version'] = getid3_lib::LittleEndian2Int(substr($MPCheaderData, $offset, 1));
274		$offset += 1;
275
276		$thisfile_mpc_header['profile']     = $this->MPCprofileNameLookup($thisfile_mpc_header['raw']['profile']);
277		$thisfile_mpc_header['sample_rate'] = $this->MPCfrequencyLookup($thisfile_mpc_header['raw']['sample_rate']);
278		if ($thisfile_mpc_header['sample_rate'] == 0) {
279			$this->error('Corrupt MPC file: frequency == zero');
280			return false;
281		}
282		$info['audio']['sample_rate'] = $thisfile_mpc_header['sample_rate'];
283		$thisfile_mpc_header['samples']       = ((($thisfile_mpc_header['frame_count'] - 1) * 1152) + $thisfile_mpc_header['last_frame_length']) * $info['audio']['channels'];
284
285		$info['playtime_seconds']     = ($thisfile_mpc_header['samples'] / $info['audio']['channels']) / $info['audio']['sample_rate'];
286		if ($info['playtime_seconds'] == 0) {
287			$this->error('Corrupt MPC file: playtime_seconds == zero');
288			return false;
289		}
290
291		// add size of file header to avdataoffset - calc bitrate correctly + MD5 data
292		$info['avdataoffset'] += $thisfile_mpc_header['size'];
293
294		$info['audio']['bitrate'] = (($info['avdataend'] - $info['avdataoffset']) * 8) / $info['playtime_seconds'];
295
296		$thisfile_mpc_header['title_peak']        = $thisfile_mpc_header['raw']['title_peak'];
297		$thisfile_mpc_header['title_peak_db']     = $this->MPCpeakDBLookup($thisfile_mpc_header['title_peak']);
298		if ($thisfile_mpc_header['raw']['title_gain'] < 0) {
299			$thisfile_mpc_header['title_gain_db'] = (float) (32768 + $thisfile_mpc_header['raw']['title_gain']) / -100;
300		} else {
301			$thisfile_mpc_header['title_gain_db'] = (float) $thisfile_mpc_header['raw']['title_gain'] / 100;
302		}
303
304		$thisfile_mpc_header['album_peak']        = $thisfile_mpc_header['raw']['album_peak'];
305		$thisfile_mpc_header['album_peak_db']     = $this->MPCpeakDBLookup($thisfile_mpc_header['album_peak']);
306		if ($thisfile_mpc_header['raw']['album_gain'] < 0) {
307			$thisfile_mpc_header['album_gain_db'] = (float) (32768 + $thisfile_mpc_header['raw']['album_gain']) / -100;
308		} else {
309			$thisfile_mpc_header['album_gain_db'] = (float) $thisfile_mpc_header['raw']['album_gain'] / 100;;
310		}
311		$thisfile_mpc_header['encoder_version']   = $this->MPCencoderVersionLookup($thisfile_mpc_header['raw']['encoder_version']);
312
313		$info['replay_gain']['track']['adjustment'] = $thisfile_mpc_header['title_gain_db'];
314		$info['replay_gain']['album']['adjustment'] = $thisfile_mpc_header['album_gain_db'];
315
316		if ($thisfile_mpc_header['title_peak'] > 0) {
317			$info['replay_gain']['track']['peak'] = $thisfile_mpc_header['title_peak'];
318		} elseif (round($thisfile_mpc_header['max_level'] * 1.18) > 0) {
319			$info['replay_gain']['track']['peak'] = getid3_lib::CastAsInt(round($thisfile_mpc_header['max_level'] * 1.18)); // why? I don't know - see mppdec.c
320		}
321		if ($thisfile_mpc_header['album_peak'] > 0) {
322			$info['replay_gain']['album']['peak'] = $thisfile_mpc_header['album_peak'];
323		}
324
325		//$info['audio']['encoder'] = 'SV'.$thisfile_mpc_header['stream_version_major'].'.'.$thisfile_mpc_header['stream_version_minor'].', '.$thisfile_mpc_header['encoder_version'];
326		$info['audio']['encoder'] = $thisfile_mpc_header['encoder_version'];
327		$info['audio']['encoder_options'] = $thisfile_mpc_header['profile'];
328		$thisfile_mpc_header['quality'] = (float) ($thisfile_mpc_header['raw']['profile'] - 5); // values can range from 0 to 15, of which 0..4 are "reserved/experimental", and 5..15 are mapped to qualities of 0.0 to 10.0
329
330		return true;
331	}
332
333	/**
334	 * @return bool
335	 */
336	public function ParseMPCsv6() {
337		// this is SV4 - SV6
338
339		$info = &$this->getid3->info;
340		$thisfile_mpc_header = &$info['mpc']['header'];
341		$offset = 0;
342
343		$thisfile_mpc_header['size'] = 8;
344		$this->fseek($info['avdataoffset']);
345		$MPCheaderData = $this->fread($thisfile_mpc_header['size']);
346
347		// add size of file header to avdataoffset - calc bitrate correctly + MD5 data
348		$info['avdataoffset'] += $thisfile_mpc_header['size'];
349
350		// Most of this code adapted from Jurgen Faul's MPEGplus source code - thanks Jurgen! :)
351		$HeaderDWORD[0] = getid3_lib::LittleEndian2Int(substr($MPCheaderData, 0, 4));
352		$HeaderDWORD[1] = getid3_lib::LittleEndian2Int(substr($MPCheaderData, 4, 4));
353
354
355		// DDDD DDDD  CCCC CCCC  BBBB BBBB  AAAA AAAA
356		// aaaa aaaa  abcd dddd  dddd deee  eeff ffff
357		//
358		// a = bitrate       = anything
359		// b = IS            = anything
360		// c = MS            = anything
361		// d = streamversion = 0000000004 or 0000000005 or 0000000006
362		// e = maxband       = anything
363		// f = blocksize     = 000001 for SV5+, anything(?) for SV4
364
365		$thisfile_mpc_header['target_bitrate']       =        (($HeaderDWORD[0] & 0xFF800000) >> 23);
366		$thisfile_mpc_header['intensity_stereo']     = (bool) (($HeaderDWORD[0] & 0x00400000) >> 22);
367		$thisfile_mpc_header['mid_side_stereo']      = (bool) (($HeaderDWORD[0] & 0x00200000) >> 21);
368		$thisfile_mpc_header['stream_version_major'] =         ($HeaderDWORD[0] & 0x001FF800) >> 11;
369		$thisfile_mpc_header['stream_version_minor'] = 0; // no sub-version numbers before SV7
370		$thisfile_mpc_header['max_band']             =         ($HeaderDWORD[0] & 0x000007C0) >>  6;  // related to lowpass frequency, not sure how it translates exactly
371		$thisfile_mpc_header['block_size']           =         ($HeaderDWORD[0] & 0x0000003F);
372
373		switch ($thisfile_mpc_header['stream_version_major']) {
374			case 4:
375				$thisfile_mpc_header['frame_count'] = ($HeaderDWORD[1] >> 16);
376				break;
377
378			case 5:
379			case 6:
380				$thisfile_mpc_header['frame_count'] =  $HeaderDWORD[1];
381				break;
382
383			default:
384				$info['error'] = 'Expecting 4, 5 or 6 in version field, found '.$thisfile_mpc_header['stream_version_major'].' instead';
385				unset($info['mpc']);
386				return false;
387		}
388
389		if (($thisfile_mpc_header['stream_version_major'] > 4) && ($thisfile_mpc_header['block_size'] != 1)) {
390			$this->warning('Block size expected to be 1, actual value found: '.$thisfile_mpc_header['block_size']);
391		}
392
393		$thisfile_mpc_header['sample_rate']   = 44100; // AB: used by all files up to SV7
394		$info['audio']['sample_rate'] = $thisfile_mpc_header['sample_rate'];
395		$thisfile_mpc_header['samples']       = $thisfile_mpc_header['frame_count'] * 1152 * $info['audio']['channels'];
396
397		if ($thisfile_mpc_header['target_bitrate'] == 0) {
398			$info['audio']['bitrate_mode'] = 'vbr';
399		} else {
400			$info['audio']['bitrate_mode'] = 'cbr';
401		}
402
403		$info['mpc']['bitrate']   = ($info['avdataend'] - $info['avdataoffset']) * 8 * 44100 / $thisfile_mpc_header['frame_count'] / 1152;
404		$info['audio']['bitrate'] = $info['mpc']['bitrate'];
405		$info['audio']['encoder'] = 'SV'.$thisfile_mpc_header['stream_version_major'];
406
407		return true;
408	}
409
410	/**
411	 * @param int $profileid
412	 *
413	 * @return string
414	 */
415	public function MPCprofileNameLookup($profileid) {
416		static $MPCprofileNameLookup = array(
417			0  => 'no profile',
418			1  => 'Experimental',
419			2  => 'unused',
420			3  => 'unused',
421			4  => 'unused',
422			5  => 'below Telephone (q = 0.0)',
423			6  => 'below Telephone (q = 1.0)',
424			7  => 'Telephone (q = 2.0)',
425			8  => 'Thumb (q = 3.0)',
426			9  => 'Radio (q = 4.0)',
427			10 => 'Standard (q = 5.0)',
428			11 => 'Extreme (q = 6.0)',
429			12 => 'Insane (q = 7.0)',
430			13 => 'BrainDead (q = 8.0)',
431			14 => 'above BrainDead (q = 9.0)',
432			15 => 'above BrainDead (q = 10.0)'
433		);
434		return (isset($MPCprofileNameLookup[$profileid]) ? $MPCprofileNameLookup[$profileid] : 'invalid');
435	}
436
437	/**
438	 * @param int $frequencyid
439	 *
440	 * @return int|string
441	 */
442	public function MPCfrequencyLookup($frequencyid) {
443		static $MPCfrequencyLookup = array(
444			0 => 44100,
445			1 => 48000,
446			2 => 37800,
447			3 => 32000
448		);
449		return (isset($MPCfrequencyLookup[$frequencyid]) ? $MPCfrequencyLookup[$frequencyid] : 'invalid');
450	}
451
452	/**
453	 * @param int $intvalue
454	 *
455	 * @return float|false
456	 */
457	public function MPCpeakDBLookup($intvalue) {
458		if ($intvalue > 0) {
459			return ((log10($intvalue) / log10(2)) - 15) * 6;
460		}
461		return false;
462	}
463
464	/**
465	 * @param int $encoderversion
466	 *
467	 * @return string
468	 */
469	public function MPCencoderVersionLookup($encoderversion) {
470		//Encoder version * 100  (106 = 1.06)
471		//EncoderVersion % 10 == 0        Release (1.0)
472		//EncoderVersion %  2 == 0        Beta (1.06)
473		//EncoderVersion %  2 == 1        Alpha (1.05a...z)
474
475		if ($encoderversion == 0) {
476			// very old version, not known exactly which
477			return 'Buschmann v1.7.0-v1.7.9 or Klemm v0.90-v1.05';
478		}
479
480		if (($encoderversion % 10) == 0) {
481
482			// release version
483			return number_format($encoderversion / 100, 2);
484
485		} elseif (($encoderversion % 2) == 0) {
486
487			// beta version
488			return number_format($encoderversion / 100, 2).' beta';
489
490		}
491
492		// alpha version
493		return number_format($encoderversion / 100, 2).' alpha';
494	}
495
496	/**
497	 * @param string $data
498	 * @param int    $packetLength
499	 * @param int    $maxHandledPacketLength
500	 *
501	 * @return int|false
502	 */
503	public function SV8variableLengthInteger($data, &$packetLength, $maxHandledPacketLength=9) {
504		$packet_size = 0;
505		for ($packetLength = 1; $packetLength <= $maxHandledPacketLength; $packetLength++) {
506			// variable-length size field:
507			//  bits, big-endian
508			//  0xxx xxxx                                           - value 0 to  2^7-1
509			//  1xxx xxxx  0xxx xxxx                                - value 0 to 2^14-1
510			//  1xxx xxxx  1xxx xxxx  0xxx xxxx                     - value 0 to 2^21-1
511			//  1xxx xxxx  1xxx xxxx  1xxx xxxx  0xxx xxxx          - value 0 to 2^28-1
512			//  ...
513			$thisbyte = ord(substr($data, ($packetLength - 1), 1));
514			// look through bytes until find a byte with MSB==0
515			$packet_size = ($packet_size << 7);
516			$packet_size = ($packet_size | ($thisbyte & 0x7F));
517			if (($thisbyte & 0x80) === 0) {
518				break;
519			}
520			if ($packetLength >= $maxHandledPacketLength) {
521				return false;
522			}
523		}
524		return $packet_size;
525	}
526
527	/**
528	 * @param string $packetKey
529	 *
530	 * @return string
531	 */
532	public function MPCsv8PacketName($packetKey) {
533		static $MPCsv8PacketName = array();
534		if (empty($MPCsv8PacketName)) {
535			$MPCsv8PacketName = array(
536				'AP' => 'Audio Packet',
537				'CT' => 'Chapter Tag',
538				'EI' => 'Encoder Info',
539				'RG' => 'Replay Gain',
540				'SE' => 'Stream End',
541				'SH' => 'Stream Header',
542				'SO' => 'Seek Table Offset',
543				'ST' => 'Seek Table',
544			);
545		}
546		return (isset($MPCsv8PacketName[$packetKey]) ? $MPCsv8PacketName[$packetKey] : $packetKey);
547	}
548}
549