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 /////////////////////////////////////////////////////////////////
8 // See readme.txt for more details //
9 /////////////////////////////////////////////////////////////////
11 // module.audio.flac.php //
12 // module for analyzing FLAC and OggFLAC audio files //
13 // dependencies: module.audio.ogg.php //
15 /////////////////////////////////////////////////////////////////
18 getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.audio.ogg.php', __FILE__, true);
21 * @tutorial http://flac.sourceforge.net/format.html
23 class getid3_flac extends getid3_handler
25 const syncword = 'fLaC';
27 public function Analyze() {
28 $info = &$this->getid3->info;
30 $this->fseek($info['avdataoffset']);
31 $StreamMarker = $this->fread(4);
32 if ($StreamMarker != self::syncword) {
33 return $this->error('Expecting "'.getid3_lib::PrintHexBytes(self::syncword).'" at offset '.$info['avdataoffset'].', found "'.getid3_lib::PrintHexBytes($StreamMarker).'"');
35 $info['fileformat'] = 'flac';
36 $info['audio']['dataformat'] = 'flac';
37 $info['audio']['bitrate_mode'] = 'vbr';
38 $info['audio']['lossless'] = true;
40 // parse flac container
41 return $this->parseMETAdata();
44 public function parseMETAdata() {
45 $info = &$this->getid3->info;
47 $BlockOffset = $this->ftell();
48 $BlockHeader = $this->fread(4);
49 $LBFBT = getid3_lib::BigEndian2Int(substr($BlockHeader, 0, 1));
50 $LastBlockFlag = (bool) ($LBFBT & 0x80);
51 $BlockType = ($LBFBT & 0x7F);
52 $BlockLength = getid3_lib::BigEndian2Int(substr($BlockHeader, 1, 3));
53 $BlockTypeText = self::metaBlockTypeLookup($BlockType);
55 if (($BlockOffset + 4 + $BlockLength) > $info['avdataend']) {
56 $this->error('METADATA_BLOCK_HEADER.BLOCK_TYPE ('.$BlockTypeText.') at offset '.$BlockOffset.' extends beyond end of file');
59 if ($BlockLength < 1) {
60 $this->error('METADATA_BLOCK_HEADER.BLOCK_LENGTH ('.$BlockLength.') at offset '.$BlockOffset.' is invalid');
64 $info['flac'][$BlockTypeText]['raw'] = array();
65 $BlockTypeText_raw = &$info['flac'][$BlockTypeText]['raw'];
67 $BlockTypeText_raw['offset'] = $BlockOffset;
68 $BlockTypeText_raw['last_meta_block'] = $LastBlockFlag;
69 $BlockTypeText_raw['block_type'] = $BlockType;
70 $BlockTypeText_raw['block_type_text'] = $BlockTypeText;
71 $BlockTypeText_raw['block_length'] = $BlockLength;
72 if ($BlockTypeText_raw['block_type'] != 0x06) { // do not read attachment data automatically
73 $BlockTypeText_raw['block_data'] = $this->fread($BlockLength);
76 switch ($BlockTypeText) {
77 case 'STREAMINFO': // 0x00
78 if (!$this->parseSTREAMINFO($BlockTypeText_raw['block_data'])) {
83 case 'PADDING': // 0x01
84 unset($info['flac']['PADDING']); // ignore
87 case 'APPLICATION': // 0x02
88 if (!$this->parseAPPLICATION($BlockTypeText_raw['block_data'])) {
93 case 'SEEKTABLE': // 0x03
94 if (!$this->parseSEEKTABLE($BlockTypeText_raw['block_data'])) {
99 case 'VORBIS_COMMENT': // 0x04
100 if (!$this->parseVORBIS_COMMENT($BlockTypeText_raw['block_data'])) {
105 case 'CUESHEET': // 0x05
106 if (!$this->parseCUESHEET($BlockTypeText_raw['block_data'])) {
111 case 'PICTURE': // 0x06
112 if (!$this->parsePICTURE()) {
118 $this->warning('Unhandled METADATA_BLOCK_HEADER.BLOCK_TYPE ('.$BlockType.') at offset '.$BlockOffset);
121 unset($info['flac'][$BlockTypeText]['raw']);
122 $info['avdataoffset'] = $this->ftell();
124 while ($LastBlockFlag === false);
127 if (!empty($info['flac']['VORBIS_COMMENT']['comments'])) {
128 $info['flac']['comments'] = $info['flac']['VORBIS_COMMENT']['comments'];
130 if (!empty($info['flac']['VORBIS_COMMENT']['vendor'])) {
131 $info['audio']['encoder'] = str_replace('reference ', '', $info['flac']['VORBIS_COMMENT']['vendor']);
134 // copy attachments to 'comments' array if nesesary
135 if (isset($info['flac']['PICTURE']) && ($this->getid3->option_save_attachments !== getID3::ATTACHMENTS_NONE)) {
136 foreach ($info['flac']['PICTURE'] as $entry) {
137 if (!empty($entry['data'])) {
138 $info['flac']['comments']['picture'][] = array('image_mime'=>$entry['image_mime'], 'data'=>$entry['data']);
143 if (isset($info['flac']['STREAMINFO'])) {
144 if (!$this->isDependencyFor('matroska')) {
145 $info['flac']['compressed_audio_bytes'] = $info['avdataend'] - $info['avdataoffset'];
147 $info['flac']['uncompressed_audio_bytes'] = $info['flac']['STREAMINFO']['samples_stream'] * $info['flac']['STREAMINFO']['channels'] * ($info['flac']['STREAMINFO']['bits_per_sample'] / 8);
148 if ($info['flac']['uncompressed_audio_bytes'] == 0) {
149 return $this->error('Corrupt FLAC file: uncompressed_audio_bytes == zero');
151 if (!empty($info['flac']['compressed_audio_bytes'])) {
152 $info['flac']['compression_ratio'] = $info['flac']['compressed_audio_bytes'] / $info['flac']['uncompressed_audio_bytes'];
156 // set md5_data_source - built into flac 0.5+
157 if (isset($info['flac']['STREAMINFO']['audio_signature'])) {
159 if ($info['flac']['STREAMINFO']['audio_signature'] === str_repeat("\x00", 16)) {
160 $this->warning('FLAC STREAMINFO.audio_signature is null (known issue with libOggFLAC)');
163 $info['md5_data_source'] = '';
164 $md5 = $info['flac']['STREAMINFO']['audio_signature'];
165 for ($i = 0; $i < strlen($md5); $i++) {
166 $info['md5_data_source'] .= str_pad(dechex(ord($md5[$i])), 2, '00', STR_PAD_LEFT);
168 if (!preg_match('/^[0-9a-f]{32}$/', $info['md5_data_source'])) {
169 unset($info['md5_data_source']);
174 if (isset($info['flac']['STREAMINFO']['bits_per_sample'])) {
175 $info['audio']['bits_per_sample'] = $info['flac']['STREAMINFO']['bits_per_sample'];
176 if ($info['audio']['bits_per_sample'] == 8) {
178 // must invert sign bit on all data bytes before MD5'ing to match FLAC's calculated value
179 // MD5sum calculates on unsigned bytes, but FLAC calculated MD5 on 8-bit audio data as signed
180 $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');
187 private function parseSTREAMINFO($BlockData) {
188 $info = &$this->getid3->info;
190 $info['flac']['STREAMINFO'] = array();
191 $streaminfo = &$info['flac']['STREAMINFO'];
193 $streaminfo['min_block_size'] = getid3_lib::BigEndian2Int(substr($BlockData, 0, 2));
194 $streaminfo['max_block_size'] = getid3_lib::BigEndian2Int(substr($BlockData, 2, 2));
195 $streaminfo['min_frame_size'] = getid3_lib::BigEndian2Int(substr($BlockData, 4, 3));
196 $streaminfo['max_frame_size'] = getid3_lib::BigEndian2Int(substr($BlockData, 7, 3));
198 $SRCSBSS = getid3_lib::BigEndian2Bin(substr($BlockData, 10, 8));
199 $streaminfo['sample_rate'] = getid3_lib::Bin2Dec(substr($SRCSBSS, 0, 20));
200 $streaminfo['channels'] = getid3_lib::Bin2Dec(substr($SRCSBSS, 20, 3)) + 1;
201 $streaminfo['bits_per_sample'] = getid3_lib::Bin2Dec(substr($SRCSBSS, 23, 5)) + 1;
202 $streaminfo['samples_stream'] = getid3_lib::Bin2Dec(substr($SRCSBSS, 28, 36));
204 $streaminfo['audio_signature'] = substr($BlockData, 18, 16);
206 if (!empty($streaminfo['sample_rate'])) {
208 $info['audio']['bitrate_mode'] = 'vbr';
209 $info['audio']['sample_rate'] = $streaminfo['sample_rate'];
210 $info['audio']['channels'] = $streaminfo['channels'];
211 $info['audio']['bits_per_sample'] = $streaminfo['bits_per_sample'];
212 $info['playtime_seconds'] = $streaminfo['samples_stream'] / $streaminfo['sample_rate'];
213 if ($info['playtime_seconds'] > 0) {
214 if (!$this->isDependencyFor('matroska')) {
215 $info['audio']['bitrate'] = (($info['avdataend'] - $info['avdataoffset']) * 8) / $info['playtime_seconds'];
218 $this->warning('Cannot determine audio bitrate because total stream size is unknown');
223 return $this->error('Corrupt METAdata block: STREAMINFO');
229 private function parseAPPLICATION($BlockData) {
230 $info = &$this->getid3->info;
232 $ApplicationID = getid3_lib::BigEndian2Int(substr($BlockData, 0, 4));
233 $info['flac']['APPLICATION'][$ApplicationID]['name'] = self::applicationIDLookup($ApplicationID);
234 $info['flac']['APPLICATION'][$ApplicationID]['data'] = substr($BlockData, 4);
239 private function parseSEEKTABLE($BlockData) {
240 $info = &$this->getid3->info;
243 $BlockLength = strlen($BlockData);
244 $placeholderpattern = str_repeat("\xFF", 8);
245 while ($offset < $BlockLength) {
246 $SampleNumberString = substr($BlockData, $offset, 8);
248 if ($SampleNumberString == $placeholderpattern) {
251 getid3_lib::safe_inc($info['flac']['SEEKTABLE']['placeholders'], 1);
256 $SampleNumber = getid3_lib::BigEndian2Int($SampleNumberString);
257 $info['flac']['SEEKTABLE'][$SampleNumber]['offset'] = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 8));
259 $info['flac']['SEEKTABLE'][$SampleNumber]['samples'] = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 2));
268 private function parseVORBIS_COMMENT($BlockData) {
269 $info = &$this->getid3->info;
271 $getid3_ogg = new getid3_ogg($this->getid3);
272 if ($this->isDependencyFor('matroska')) {
273 $getid3_ogg->setStringMode($this->data_string);
275 $getid3_ogg->ParseVorbisComments();
276 if (isset($info['ogg'])) {
277 unset($info['ogg']['comments_raw']);
278 $info['flac']['VORBIS_COMMENT'] = $info['ogg'];
287 private function parseCUESHEET($BlockData) {
288 $info = &$this->getid3->info;
290 $info['flac']['CUESHEET']['media_catalog_number'] = trim(substr($BlockData, $offset, 128), "\0");
292 $info['flac']['CUESHEET']['lead_in_samples'] = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 8));
294 $info['flac']['CUESHEET']['flags']['is_cd'] = (bool) (getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1)) & 0x80);
297 $offset += 258; // reserved
299 $info['flac']['CUESHEET']['number_tracks'] = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1));
302 for ($track = 0; $track < $info['flac']['CUESHEET']['number_tracks']; $track++) {
303 $TrackSampleOffset = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 8));
305 $TrackNumber = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1));
308 $info['flac']['CUESHEET']['tracks'][$TrackNumber]['sample_offset'] = $TrackSampleOffset;
310 $info['flac']['CUESHEET']['tracks'][$TrackNumber]['isrc'] = substr($BlockData, $offset, 12);
313 $TrackFlagsRaw = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1));
315 $info['flac']['CUESHEET']['tracks'][$TrackNumber]['flags']['is_audio'] = (bool) ($TrackFlagsRaw & 0x80);
316 $info['flac']['CUESHEET']['tracks'][$TrackNumber]['flags']['pre_emphasis'] = (bool) ($TrackFlagsRaw & 0x40);
318 $offset += 13; // reserved
320 $info['flac']['CUESHEET']['tracks'][$TrackNumber]['index_points'] = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1));
323 for ($index = 0; $index < $info['flac']['CUESHEET']['tracks'][$TrackNumber]['index_points']; $index++) {
324 $IndexSampleOffset = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 8));
326 $IndexNumber = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1));
329 $offset += 3; // reserved
331 $info['flac']['CUESHEET']['tracks'][$TrackNumber]['indexes'][$IndexNumber] = $IndexSampleOffset;
339 * Parse METADATA_BLOCK_PICTURE flac structure and extract attachment
340 * External usage: audio.ogg
342 public function parsePICTURE() {
343 $info = &$this->getid3->info;
345 $picture['typeid'] = getid3_lib::BigEndian2Int($this->fread(4));
346 $picture['type'] = self::pictureTypeLookup($picture['typeid']);
347 $picture['image_mime'] = $this->fread(getid3_lib::BigEndian2Int($this->fread(4)));
348 $descr_length = getid3_lib::BigEndian2Int($this->fread(4));
350 $picture['description'] = $this->fread($descr_length);
352 $picture['width'] = getid3_lib::BigEndian2Int($this->fread(4));
353 $picture['height'] = getid3_lib::BigEndian2Int($this->fread(4));
354 $picture['color_depth'] = getid3_lib::BigEndian2Int($this->fread(4));
355 $picture['colors_indexed'] = getid3_lib::BigEndian2Int($this->fread(4));
356 $data_length = getid3_lib::BigEndian2Int($this->fread(4));
358 if ($picture['image_mime'] == '-->') {
359 $picture['data'] = $this->fread($data_length);
361 $picture['data'] = $this->saveAttachment(
362 str_replace('/', '_', $picture['type']).'_'.$this->ftell(),
365 $picture['image_mime']);
368 $info['flac']['PICTURE'][] = $picture;
373 public static function metaBlockTypeLookup($blocktype) {
374 static $lookup = array(
379 4 => 'VORBIS_COMMENT',
383 return (isset($lookup[$blocktype]) ? $lookup[$blocktype] : 'reserved');
386 public static function applicationIDLookup($applicationid) {
387 // http://flac.sourceforge.net/id.html
388 static $lookup = array(
389 0x41544348 => 'FlacFile', // "ATCH"
390 0x42534F4C => 'beSolo', // "BSOL"
391 0x42554753 => 'Bugs Player', // "BUGS"
392 0x43756573 => 'GoldWave cue points (specification)', // "Cues"
393 0x46696361 => 'CUE Splitter', // "Fica"
394 0x46746F6C => 'flac-tools', // "Ftol"
395 0x4D4F5442 => 'MOTB MetaCzar', // "MOTB"
396 0x4D505345 => 'MP3 Stream Editor', // "MPSE"
397 0x4D754D4C => 'MusicML: Music Metadata Language', // "MuML"
398 0x52494646 => 'Sound Devices RIFF chunk storage', // "RIFF"
399 0x5346464C => 'Sound Font FLAC', // "SFFL"
400 0x534F4E59 => 'Sony Creative Software', // "SONY"
401 0x5351455A => 'flacsqueeze', // "SQEZ"
402 0x54745776 => 'TwistedWave', // "TtWv"
403 0x55495453 => 'UITS Embedding tools', // "UITS"
404 0x61696666 => 'FLAC AIFF chunk storage', // "aiff"
405 0x696D6167 => 'flac-image application for storing arbitrary files in APPLICATION metadata blocks', // "imag"
406 0x7065656D => 'Parseable Embedded Extensible Metadata (specification)', // "peem"
407 0x71667374 => 'QFLAC Studio', // "qfst"
408 0x72696666 => 'FLAC RIFF chunk storage', // "riff"
409 0x74756E65 => 'TagTuner', // "tune"
410 0x78626174 => 'XBAT', // "xbat"
411 0x786D6364 => 'xmcd', // "xmcd"
413 return (isset($lookup[$applicationid]) ? $lookup[$applicationid] : 'reserved');
416 public static function pictureTypeLookup($type_id) {
417 static $lookup = array (
419 1 => '32x32 pixels \'file icon\' (PNG only)',
420 2 => 'Other file icon',
421 3 => 'Cover (front)',
424 6 => 'Media (e.g. label side of CD)',
425 7 => 'Lead artist/lead performer/soloist',
426 8 => 'Artist/performer',
428 10 => 'Band/Orchestra',
430 12 => 'Lyricist/text writer',
431 13 => 'Recording Location',
432 14 => 'During recording',
433 15 => 'During performance',
434 16 => 'Movie/video screen capture',
435 17 => 'A bright coloured fish',
436 18 => 'Illustration',
437 19 => 'Band/artist logotype',
438 20 => 'Publisher/Studio logotype',
440 return (isset($lookup[$type_id]) ? $lookup[$type_id] : 'reserved');