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