]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/ID3/module.audio.flac.php
Wordpress 3.6
[autoinstalls/wordpress.git] / wp-includes / ID3 / module.audio.flac.php
1 <?php
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 /////////////////////////////////////////////////////////////////
9 //                                                             //
10 // module.audio.flac.php                                       //
11 // module for analyzing FLAC and OggFLAC audio files           //
12 // dependencies: module.audio.ogg.php                          //
13 //                                                            ///
14 /////////////////////////////////////////////////////////////////
15
16
17 getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.audio.ogg.php', __FILE__, true);
18
19 /**
20 * @tutorial http://flac.sourceforge.net/format.html
21 */
22 class getid3_flac extends getid3_handler
23 {
24         const syncword = 'fLaC';
25
26         public function Analyze() {
27                 $info = &$this->getid3->info;
28
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).'"');
33                 }
34                 $info['fileformat']            = 'flac';
35                 $info['audio']['dataformat']   = 'flac';
36                 $info['audio']['bitrate_mode'] = 'vbr';
37                 $info['audio']['lossless']     = true;
38
39                 // parse flac container
40                 return $this->parseMETAdata();
41         }
42
43         public function parseMETAdata() {
44                 $info = &$this->getid3->info;
45                 do {
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);
53
54                         if (($BlockOffset + 4 + $BlockLength) > $info['avdataend']) {
55                                 $this->error('METADATA_BLOCK_HEADER.BLOCK_TYPE ('.$BlockTypeText.') at offset '.$BlockOffset.' extends beyond end of file');
56                                 break;
57                         }
58                         if ($BlockLength < 1) {
59                                 $this->error('METADATA_BLOCK_HEADER.BLOCK_LENGTH ('.$BlockLength.') at offset '.$BlockOffset.' is invalid');
60                                 break;
61                         }
62
63                         $info['flac'][$BlockTypeText]['raw'] = array();
64                         $BlockTypeText_raw = &$info['flac'][$BlockTypeText]['raw'];
65
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);
73                         }
74
75                         switch ($BlockTypeText) {
76                                 case 'STREAMINFO':     // 0x00
77                                         if (!$this->parseSTREAMINFO($BlockTypeText_raw['block_data'])) {
78                                                 return false;
79                                         }
80                                         break;
81
82                                 case 'PADDING':        // 0x01
83                                         unset($info['flac']['PADDING']); // ignore
84                                         break;
85
86                                 case 'APPLICATION':    // 0x02
87                                         if (!$this->parseAPPLICATION($BlockTypeText_raw['block_data'])) {
88                                                 return false;
89                                         }
90                                         break;
91
92                                 case 'SEEKTABLE':      // 0x03
93                                         if (!$this->parseSEEKTABLE($BlockTypeText_raw['block_data'])) {
94                                                 return false;
95                                         }
96                                         break;
97
98                                 case 'VORBIS_COMMENT': // 0x04
99                                         if (!$this->parseVORBIS_COMMENT($BlockTypeText_raw['block_data'])) {
100                                                 return false;
101                                         }
102                                         break;
103
104                                 case 'CUESHEET':       // 0x05
105                                         if (!$this->parseCUESHEET($BlockTypeText_raw['block_data'])) {
106                                                 return false;
107                                         }
108                                         break;
109
110                                 case 'PICTURE':        // 0x06
111                                         if (!$this->parsePICTURE()) {
112                                                 return false;
113                                         }
114                                         break;
115
116                                 default:
117                                         $this->warning('Unhandled METADATA_BLOCK_HEADER.BLOCK_TYPE ('.$BlockType.') at offset '.$BlockOffset);
118                         }
119
120                         unset($info['flac'][$BlockTypeText]['raw']);
121                         $info['avdataoffset'] = $this->ftell();
122                 }
123                 while ($LastBlockFlag === false);
124
125                 // handle tags
126                 if (!empty($info['flac']['VORBIS_COMMENT']['comments'])) {
127                         $info['flac']['comments'] = $info['flac']['VORBIS_COMMENT']['comments'];
128                 }
129                 if (!empty($info['flac']['VORBIS_COMMENT']['vendor'])) {
130                         $info['audio']['encoder'] = str_replace('reference ', '', $info['flac']['VORBIS_COMMENT']['vendor']);
131                 }
132
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']);
138                                 }
139                         }
140                 }
141
142                 if (isset($info['flac']['STREAMINFO'])) {
143                         if (!$this->isDependencyFor('matroska')) {
144                                 $info['flac']['compressed_audio_bytes'] = $info['avdataend'] - $info['avdataoffset'];
145                         }
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');
149                         }
150                         if (!empty($info['flac']['compressed_audio_bytes'])) {
151                                 $info['flac']['compression_ratio'] = $info['flac']['compressed_audio_bytes'] / $info['flac']['uncompressed_audio_bytes'];
152                         }
153                 }
154
155                 // set md5_data_source - built into flac 0.5+
156                 if (isset($info['flac']['STREAMINFO']['audio_signature'])) {
157
158                         if ($info['flac']['STREAMINFO']['audio_signature'] === str_repeat("\x00", 16)) {
159                 $this->warning('FLAC STREAMINFO.audio_signature is null (known issue with libOggFLAC)');
160                         }
161                         else {
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);
166                                 }
167                                 if (!preg_match('/^[0-9a-f]{32}$/', $info['md5_data_source'])) {
168                                         unset($info['md5_data_source']);
169                                 }
170                         }
171                 }
172
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) {
176                                 // special case
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');
180                         }
181                 }
182
183                 return true;
184         }
185
186         private function parseSTREAMINFO($BlockData) {
187                 $info = &$this->getid3->info;
188
189                 $info['flac']['STREAMINFO'] = array();
190                 $streaminfo = &$info['flac']['STREAMINFO'];
191
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));
196
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));
202
203                 $streaminfo['audio_signature'] = substr($BlockData, 18, 16);
204
205                 if (!empty($streaminfo['sample_rate'])) {
206
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'];
215                                 }
216                                 else {
217                                         $this->warning('Cannot determine audio bitrate because total stream size is unknown');
218                                 }
219                         }
220
221                 } else {
222                         return $this->error('Corrupt METAdata block: STREAMINFO');
223                 }
224
225                 return true;
226         }
227
228         private function parseAPPLICATION($BlockData) {
229                 $info = &$this->getid3->info;
230
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);
234
235                 return true;
236         }
237
238         private function parseSEEKTABLE($BlockData) {
239                 $info = &$this->getid3->info;
240
241                 $offset = 0;
242                 $BlockLength = strlen($BlockData);
243                 $placeholderpattern = str_repeat("\xFF", 8);
244                 while ($offset < $BlockLength) {
245                         $SampleNumberString = substr($BlockData, $offset, 8);
246                         $offset += 8;
247                         if ($SampleNumberString == $placeholderpattern) {
248
249                                 // placeholder point
250                                 getid3_lib::safe_inc($info['flac']['SEEKTABLE']['placeholders'], 1);
251                                 $offset += 10;
252
253                         } else {
254
255                                 $SampleNumber                                        = getid3_lib::BigEndian2Int($SampleNumberString);
256                                 $info['flac']['SEEKTABLE'][$SampleNumber]['offset']  = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 8));
257                                 $offset += 8;
258                                 $info['flac']['SEEKTABLE'][$SampleNumber]['samples'] = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 2));
259                                 $offset += 2;
260
261                         }
262                 }
263
264                 return true;
265         }
266
267         private function parseVORBIS_COMMENT($BlockData) {
268                 $info = &$this->getid3->info;
269
270                 $getid3_ogg = new getid3_ogg($this->getid3);
271                 if ($this->isDependencyFor('matroska')) {
272                         $getid3_ogg->setStringMode($this->data_string);
273                 }
274                 $getid3_ogg->ParseVorbisComments();
275                 if (isset($info['ogg'])) {
276                         unset($info['ogg']['comments_raw']);
277                         $info['flac']['VORBIS_COMMENT'] = $info['ogg'];
278                         unset($info['ogg']);
279                 }
280
281                 unset($getid3_ogg);
282
283                 return true;
284         }
285
286         private function parseCUESHEET($BlockData) {
287                 $info = &$this->getid3->info;
288                 $offset = 0;
289                 $info['flac']['CUESHEET']['media_catalog_number'] =                              trim(substr($BlockData, $offset, 128), "\0");
290                 $offset += 128;
291                 $info['flac']['CUESHEET']['lead_in_samples']      =         getid3_lib::BigEndian2Int(substr($BlockData, $offset, 8));
292                 $offset += 8;
293                 $info['flac']['CUESHEET']['flags']['is_cd']       = (bool) (getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1)) & 0x80);
294                 $offset += 1;
295
296                 $offset += 258; // reserved
297
298                 $info['flac']['CUESHEET']['number_tracks']        =         getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1));
299                 $offset += 1;
300
301                 for ($track = 0; $track < $info['flac']['CUESHEET']['number_tracks']; $track++) {
302                         $TrackSampleOffset = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 8));
303                         $offset += 8;
304                         $TrackNumber       = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1));
305                         $offset += 1;
306
307                         $info['flac']['CUESHEET']['tracks'][$TrackNumber]['sample_offset']         = $TrackSampleOffset;
308
309                         $info['flac']['CUESHEET']['tracks'][$TrackNumber]['isrc']                  =                           substr($BlockData, $offset, 12);
310                         $offset += 12;
311
312                         $TrackFlagsRaw                                                             = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1));
313                         $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);
316
317                         $offset += 13; // reserved
318
319                         $info['flac']['CUESHEET']['tracks'][$TrackNumber]['index_points']          = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1));
320                         $offset += 1;
321
322                         for ($index = 0; $index < $info['flac']['CUESHEET']['tracks'][$TrackNumber]['index_points']; $index++) {
323                                 $IndexSampleOffset = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 8));
324                                 $offset += 8;
325                                 $IndexNumber       = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1));
326                                 $offset += 1;
327
328                                 $offset += 3; // reserved
329
330                                 $info['flac']['CUESHEET']['tracks'][$TrackNumber]['indexes'][$IndexNumber] = $IndexSampleOffset;
331                         }
332                 }
333
334                 return true;
335         }
336
337         /**
338         * Parse METADATA_BLOCK_PICTURE flac structure and extract attachment
339         * External usage: audio.ogg
340         */
341         public function parsePICTURE() {
342                 $info = &$this->getid3->info;
343
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));
348                 if ($descr_length) {
349                         $picture['description'] = $this->fread($descr_length);
350                 }
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));
356
357                 if ($picture['image_mime'] == '-->') {
358                         $picture['data'] = $this->fread($data_length);
359                 } else {
360                         $picture['data'] = $this->saveAttachment(
361                                 str_replace('/', '_', $picture['type']).'_'.$this->ftell(),
362                                 $this->ftell(),
363                                 $data_length,
364                                 $picture['image_mime']);
365                 }
366
367                 $info['flac']['PICTURE'][] = $picture;
368
369                 return true;
370         }
371
372         public static function metaBlockTypeLookup($blocktype) {
373                 static $lookup = array(
374                         0 => 'STREAMINFO',
375                         1 => 'PADDING',
376                         2 => 'APPLICATION',
377                         3 => 'SEEKTABLE',
378                         4 => 'VORBIS_COMMENT',
379                         5 => 'CUESHEET',
380                         6 => 'PICTURE',
381                 );
382                 return (isset($lookup[$blocktype]) ? $lookup[$blocktype] : 'reserved');
383         }
384
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"
411                 );
412                 return (isset($lookup[$applicationid]) ? $lookup[$applicationid] : 'reserved');
413         }
414
415         public static function pictureTypeLookup($type_id) {
416                 static $lookup = array (
417                          0 => 'Other',
418                          1 => '32x32 pixels \'file icon\' (PNG only)',
419                          2 => 'Other file icon',
420                          3 => 'Cover (front)',
421                          4 => 'Cover (back)',
422                          5 => 'Leaflet page',
423                          6 => 'Media (e.g. label side of CD)',
424                          7 => 'Lead artist/lead performer/soloist',
425                          8 => 'Artist/performer',
426                          9 => 'Conductor',
427                         10 => 'Band/Orchestra',
428                         11 => 'Composer',
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',
438                 );
439                 return (isset($lookup[$type_id]) ? $lookup[$type_id] : 'reserved');
440         }
441
442 }