2 /////////////////////////////////////////////////////////////////
3 /// getID3() by James Heinrich <info@getid3.org> //
4 // available at http://getid3.sourceforge.net //
5 // or http://www.getid3.org //
6 /////////////////////////////////////////////////////////////////
7 // See readme.txt for more details //
8 /////////////////////////////////////////////////////////////////
10 // module.audio.flac.php //
11 // module for analyzing FLAC and OggFLAC audio files //
12 // dependencies: module.audio.ogg.php //
14 /////////////////////////////////////////////////////////////////
17 getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.audio.ogg.php', __FILE__, true);
20 * @tutorial http://flac.sourceforge.net/format.html
22 class getid3_flac extends getid3_handler
24 const syncword = 'fLaC';
26 public function Analyze() {
27 $info = &$this->getid3->info;
29 $this->fseek($info['avdataoffset']);
30 $StreamMarker = $this->fread(4);
31 if ($StreamMarker != self::syncword) {
32 return $this->error('Expecting "'.getid3_lib::PrintHexBytes(self::syncword).'" at offset '.$info['avdataoffset'].', found "'.getid3_lib::PrintHexBytes($StreamMarker).'"');
34 $info['fileformat'] = 'flac';
35 $info['audio']['dataformat'] = 'flac';
36 $info['audio']['bitrate_mode'] = 'vbr';
37 $info['audio']['lossless'] = true;
39 // parse flac container
40 return $this->parseMETAdata();
43 public function parseMETAdata() {
44 $info = &$this->getid3->info;
46 $BlockOffset = $this->ftell();
47 $BlockHeader = $this->fread(4);
48 $LBFBT = getid3_lib::BigEndian2Int(substr($BlockHeader, 0, 1));
49 $LastBlockFlag = (bool) ($LBFBT & 0x80);
50 $BlockType = ($LBFBT & 0x7F);
51 $BlockLength = getid3_lib::BigEndian2Int(substr($BlockHeader, 1, 3));
52 $BlockTypeText = self::metaBlockTypeLookup($BlockType);
54 if (($BlockOffset + 4 + $BlockLength) > $info['avdataend']) {
55 $this->error('METADATA_BLOCK_HEADER.BLOCK_TYPE ('.$BlockTypeText.') at offset '.$BlockOffset.' extends beyond end of file');
58 if ($BlockLength < 1) {
59 $this->error('METADATA_BLOCK_HEADER.BLOCK_LENGTH ('.$BlockLength.') at offset '.$BlockOffset.' is invalid');
63 $info['flac'][$BlockTypeText]['raw'] = array();
64 $BlockTypeText_raw = &$info['flac'][$BlockTypeText]['raw'];
66 $BlockTypeText_raw['offset'] = $BlockOffset;
67 $BlockTypeText_raw['last_meta_block'] = $LastBlockFlag;
68 $BlockTypeText_raw['block_type'] = $BlockType;
69 $BlockTypeText_raw['block_type_text'] = $BlockTypeText;
70 $BlockTypeText_raw['block_length'] = $BlockLength;
71 if ($BlockTypeText_raw['block_type'] != 0x06) { // do not read attachment data automatically
72 $BlockTypeText_raw['block_data'] = $this->fread($BlockLength);
75 switch ($BlockTypeText) {
76 case 'STREAMINFO': // 0x00
77 if (!$this->parseSTREAMINFO($BlockTypeText_raw['block_data'])) {
82 case 'PADDING': // 0x01
83 unset($info['flac']['PADDING']); // ignore
86 case 'APPLICATION': // 0x02
87 if (!$this->parseAPPLICATION($BlockTypeText_raw['block_data'])) {
92 case 'SEEKTABLE': // 0x03
93 if (!$this->parseSEEKTABLE($BlockTypeText_raw['block_data'])) {
98 case 'VORBIS_COMMENT': // 0x04
99 if (!$this->parseVORBIS_COMMENT($BlockTypeText_raw['block_data'])) {
104 case 'CUESHEET': // 0x05
105 if (!$this->parseCUESHEET($BlockTypeText_raw['block_data'])) {
110 case 'PICTURE': // 0x06
111 if (!$this->parsePICTURE()) {
117 $this->warning('Unhandled METADATA_BLOCK_HEADER.BLOCK_TYPE ('.$BlockType.') at offset '.$BlockOffset);
120 unset($info['flac'][$BlockTypeText]['raw']);
121 $info['avdataoffset'] = $this->ftell();
123 while ($LastBlockFlag === false);
126 if (!empty($info['flac']['VORBIS_COMMENT']['comments'])) {
127 $info['flac']['comments'] = $info['flac']['VORBIS_COMMENT']['comments'];
129 if (!empty($info['flac']['VORBIS_COMMENT']['vendor'])) {
130 $info['audio']['encoder'] = str_replace('reference ', '', $info['flac']['VORBIS_COMMENT']['vendor']);
133 // copy attachments to 'comments' array if nesesary
134 if (isset($info['flac']['PICTURE']) && ($this->getid3->option_save_attachments !== getID3::ATTACHMENTS_NONE)) {
135 foreach ($info['flac']['PICTURE'] as $entry) {
136 if (!empty($entry['data'])) {
137 $info['flac']['comments']['picture'][] = array('image_mime'=>$entry['image_mime'], 'data'=>$entry['data']);
142 if (isset($info['flac']['STREAMINFO'])) {
143 if (!$this->isDependencyFor('matroska')) {
144 $info['flac']['compressed_audio_bytes'] = $info['avdataend'] - $info['avdataoffset'];
146 $info['flac']['uncompressed_audio_bytes'] = $info['flac']['STREAMINFO']['samples_stream'] * $info['flac']['STREAMINFO']['channels'] * ($info['flac']['STREAMINFO']['bits_per_sample'] / 8);
147 if ($info['flac']['uncompressed_audio_bytes'] == 0) {
148 return $this->error('Corrupt FLAC file: uncompressed_audio_bytes == zero');
150 if (!empty($info['flac']['compressed_audio_bytes'])) {
151 $info['flac']['compression_ratio'] = $info['flac']['compressed_audio_bytes'] / $info['flac']['uncompressed_audio_bytes'];
155 // set md5_data_source - built into flac 0.5+
156 if (isset($info['flac']['STREAMINFO']['audio_signature'])) {
158 if ($info['flac']['STREAMINFO']['audio_signature'] === str_repeat("\x00", 16)) {
159 $this->warning('FLAC STREAMINFO.audio_signature is null (known issue with libOggFLAC)');
162 $info['md5_data_source'] = '';
163 $md5 = $info['flac']['STREAMINFO']['audio_signature'];
164 for ($i = 0; $i < strlen($md5); $i++) {
165 $info['md5_data_source'] .= str_pad(dechex(ord($md5[$i])), 2, '00', STR_PAD_LEFT);
167 if (!preg_match('/^[0-9a-f]{32}$/', $info['md5_data_source'])) {
168 unset($info['md5_data_source']);
173 if (isset($info['flac']['STREAMINFO']['bits_per_sample'])) {
174 $info['audio']['bits_per_sample'] = $info['flac']['STREAMINFO']['bits_per_sample'];
175 if ($info['audio']['bits_per_sample'] == 8) {
177 // must invert sign bit on all data bytes before MD5'ing to match FLAC's calculated value
178 // MD5sum calculates on unsigned bytes, but FLAC calculated MD5 on 8-bit audio data as signed
179 $this->warning('FLAC calculates MD5 data strangely on 8-bit audio, so the stored md5_data_source value will not match the decoded WAV file');
186 private function parseSTREAMINFO($BlockData) {
187 $info = &$this->getid3->info;
189 $info['flac']['STREAMINFO'] = array();
190 $streaminfo = &$info['flac']['STREAMINFO'];
192 $streaminfo['min_block_size'] = getid3_lib::BigEndian2Int(substr($BlockData, 0, 2));
193 $streaminfo['max_block_size'] = getid3_lib::BigEndian2Int(substr($BlockData, 2, 2));
194 $streaminfo['min_frame_size'] = getid3_lib::BigEndian2Int(substr($BlockData, 4, 3));
195 $streaminfo['max_frame_size'] = getid3_lib::BigEndian2Int(substr($BlockData, 7, 3));
197 $SRCSBSS = getid3_lib::BigEndian2Bin(substr($BlockData, 10, 8));
198 $streaminfo['sample_rate'] = getid3_lib::Bin2Dec(substr($SRCSBSS, 0, 20));
199 $streaminfo['channels'] = getid3_lib::Bin2Dec(substr($SRCSBSS, 20, 3)) + 1;
200 $streaminfo['bits_per_sample'] = getid3_lib::Bin2Dec(substr($SRCSBSS, 23, 5)) + 1;
201 $streaminfo['samples_stream'] = getid3_lib::Bin2Dec(substr($SRCSBSS, 28, 36));
203 $streaminfo['audio_signature'] = substr($BlockData, 18, 16);
205 if (!empty($streaminfo['sample_rate'])) {
207 $info['audio']['bitrate_mode'] = 'vbr';
208 $info['audio']['sample_rate'] = $streaminfo['sample_rate'];
209 $info['audio']['channels'] = $streaminfo['channels'];
210 $info['audio']['bits_per_sample'] = $streaminfo['bits_per_sample'];
211 $info['playtime_seconds'] = $streaminfo['samples_stream'] / $streaminfo['sample_rate'];
212 if ($info['playtime_seconds'] > 0) {
213 if (!$this->isDependencyFor('matroska')) {
214 $info['audio']['bitrate'] = (($info['avdataend'] - $info['avdataoffset']) * 8) / $info['playtime_seconds'];
217 $this->warning('Cannot determine audio bitrate because total stream size is unknown');
222 return $this->error('Corrupt METAdata block: STREAMINFO');
228 private function parseAPPLICATION($BlockData) {
229 $info = &$this->getid3->info;
231 $ApplicationID = getid3_lib::BigEndian2Int(substr($BlockData, 0, 4));
232 $info['flac']['APPLICATION'][$ApplicationID]['name'] = self::applicationIDLookup($ApplicationID);
233 $info['flac']['APPLICATION'][$ApplicationID]['data'] = substr($BlockData, 4);
238 private function parseSEEKTABLE($BlockData) {
239 $info = &$this->getid3->info;
242 $BlockLength = strlen($BlockData);
243 $placeholderpattern = str_repeat("\xFF", 8);
244 while ($offset < $BlockLength) {
245 $SampleNumberString = substr($BlockData, $offset, 8);
247 if ($SampleNumberString == $placeholderpattern) {
250 getid3_lib::safe_inc($info['flac']['SEEKTABLE']['placeholders'], 1);
255 $SampleNumber = getid3_lib::BigEndian2Int($SampleNumberString);
256 $info['flac']['SEEKTABLE'][$SampleNumber]['offset'] = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 8));
258 $info['flac']['SEEKTABLE'][$SampleNumber]['samples'] = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 2));
267 private function parseVORBIS_COMMENT($BlockData) {
268 $info = &$this->getid3->info;
270 $getid3_ogg = new getid3_ogg($this->getid3);
271 if ($this->isDependencyFor('matroska')) {
272 $getid3_ogg->setStringMode($this->data_string);
274 $getid3_ogg->ParseVorbisComments();
275 if (isset($info['ogg'])) {
276 unset($info['ogg']['comments_raw']);
277 $info['flac']['VORBIS_COMMENT'] = $info['ogg'];
286 private function parseCUESHEET($BlockData) {
287 $info = &$this->getid3->info;
289 $info['flac']['CUESHEET']['media_catalog_number'] = trim(substr($BlockData, $offset, 128), "\0");
291 $info['flac']['CUESHEET']['lead_in_samples'] = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 8));
293 $info['flac']['CUESHEET']['flags']['is_cd'] = (bool) (getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1)) & 0x80);
296 $offset += 258; // reserved
298 $info['flac']['CUESHEET']['number_tracks'] = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1));
301 for ($track = 0; $track < $info['flac']['CUESHEET']['number_tracks']; $track++) {
302 $TrackSampleOffset = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 8));
304 $TrackNumber = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1));
307 $info['flac']['CUESHEET']['tracks'][$TrackNumber]['sample_offset'] = $TrackSampleOffset;
309 $info['flac']['CUESHEET']['tracks'][$TrackNumber]['isrc'] = substr($BlockData, $offset, 12);
312 $TrackFlagsRaw = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1));
314 $info['flac']['CUESHEET']['tracks'][$TrackNumber]['flags']['is_audio'] = (bool) ($TrackFlagsRaw & 0x80);
315 $info['flac']['CUESHEET']['tracks'][$TrackNumber]['flags']['pre_emphasis'] = (bool) ($TrackFlagsRaw & 0x40);
317 $offset += 13; // reserved
319 $info['flac']['CUESHEET']['tracks'][$TrackNumber]['index_points'] = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1));
322 for ($index = 0; $index < $info['flac']['CUESHEET']['tracks'][$TrackNumber]['index_points']; $index++) {
323 $IndexSampleOffset = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 8));
325 $IndexNumber = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1));
328 $offset += 3; // reserved
330 $info['flac']['CUESHEET']['tracks'][$TrackNumber]['indexes'][$IndexNumber] = $IndexSampleOffset;
338 * Parse METADATA_BLOCK_PICTURE flac structure and extract attachment
339 * External usage: audio.ogg
341 public function parsePICTURE() {
342 $info = &$this->getid3->info;
344 $picture['typeid'] = getid3_lib::BigEndian2Int($this->fread(4));
345 $picture['type'] = self::pictureTypeLookup($picture['typeid']);
346 $picture['image_mime'] = $this->fread(getid3_lib::BigEndian2Int($this->fread(4)));
347 $descr_length = getid3_lib::BigEndian2Int($this->fread(4));
349 $picture['description'] = $this->fread($descr_length);
351 $picture['width'] = getid3_lib::BigEndian2Int($this->fread(4));
352 $picture['height'] = getid3_lib::BigEndian2Int($this->fread(4));
353 $picture['color_depth'] = getid3_lib::BigEndian2Int($this->fread(4));
354 $picture['colors_indexed'] = getid3_lib::BigEndian2Int($this->fread(4));
355 $data_length = getid3_lib::BigEndian2Int($this->fread(4));
357 if ($picture['image_mime'] == '-->') {
358 $picture['data'] = $this->fread($data_length);
360 $picture['data'] = $this->saveAttachment(
361 str_replace('/', '_', $picture['type']).'_'.$this->ftell(),
364 $picture['image_mime']);
367 $info['flac']['PICTURE'][] = $picture;
372 public static function metaBlockTypeLookup($blocktype) {
373 static $lookup = array(
378 4 => 'VORBIS_COMMENT',
382 return (isset($lookup[$blocktype]) ? $lookup[$blocktype] : 'reserved');
385 public static function applicationIDLookup($applicationid) {
386 // http://flac.sourceforge.net/id.html
387 static $lookup = array(
388 0x41544348 => 'FlacFile', // "ATCH"
389 0x42534F4C => 'beSolo', // "BSOL"
390 0x42554753 => 'Bugs Player', // "BUGS"
391 0x43756573 => 'GoldWave cue points (specification)', // "Cues"
392 0x46696361 => 'CUE Splitter', // "Fica"
393 0x46746F6C => 'flac-tools', // "Ftol"
394 0x4D4F5442 => 'MOTB MetaCzar', // "MOTB"
395 0x4D505345 => 'MP3 Stream Editor', // "MPSE"
396 0x4D754D4C => 'MusicML: Music Metadata Language', // "MuML"
397 0x52494646 => 'Sound Devices RIFF chunk storage', // "RIFF"
398 0x5346464C => 'Sound Font FLAC', // "SFFL"
399 0x534F4E59 => 'Sony Creative Software', // "SONY"
400 0x5351455A => 'flacsqueeze', // "SQEZ"
401 0x54745776 => 'TwistedWave', // "TtWv"
402 0x55495453 => 'UITS Embedding tools', // "UITS"
403 0x61696666 => 'FLAC AIFF chunk storage', // "aiff"
404 0x696D6167 => 'flac-image application for storing arbitrary files in APPLICATION metadata blocks', // "imag"
405 0x7065656D => 'Parseable Embedded Extensible Metadata (specification)', // "peem"
406 0x71667374 => 'QFLAC Studio', // "qfst"
407 0x72696666 => 'FLAC RIFF chunk storage', // "riff"
408 0x74756E65 => 'TagTuner', // "tune"
409 0x78626174 => 'XBAT', // "xbat"
410 0x786D6364 => 'xmcd', // "xmcd"
412 return (isset($lookup[$applicationid]) ? $lookup[$applicationid] : 'reserved');
415 public static function pictureTypeLookup($type_id) {
416 static $lookup = array (
418 1 => '32x32 pixels \'file icon\' (PNG only)',
419 2 => 'Other file icon',
420 3 => 'Cover (front)',
423 6 => 'Media (e.g. label side of CD)',
424 7 => 'Lead artist/lead performer/soloist',
425 8 => 'Artist/performer',
427 10 => 'Band/Orchestra',
429 12 => 'Lyricist/text writer',
430 13 => 'Recording Location',
431 14 => 'During recording',
432 15 => 'During performance',
433 16 => 'Movie/video screen capture',
434 17 => 'A bright coloured fish',
435 18 => 'Illustration',
436 19 => 'Band/artist logotype',
437 20 => 'Publisher/Studio logotype',
439 return (isset($lookup[$type_id]) ? $lookup[$type_id] : 'reserved');