Completed
Pull Request — master (#2)
by Stephen
09:27
created

getid3_flac::parseMETAdata()   F

Complexity

Conditions 37
Paths 8940

Size

Total Lines 152
Code Lines 96

Duplication

Lines 13
Ratio 8.55 %

Importance

Changes 0
Metric Value
cc 37
eloc 96
nc 8940
nop 0
dl 13
loc 152
rs 2
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/////////////////////////////////////////////////////////////////
3
/// getID3() by James Heinrich <[email protected]>               //
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
					if (!isset($info['flac']['comments']['picture'])) {
139
						$info['flac']['comments']['picture'] = array();
140
					}
141
					$comments_picture_data = array();
142
					foreach (array('data', 'image_mime', 'image_width', 'image_height', 'imagetype', 'picturetype', 'description', 'datalength') as $picture_key) {
143
						if (isset($entry[$picture_key])) {
144
							$comments_picture_data[$picture_key] = $entry[$picture_key];
145
						}
146
					}
147
					$info['flac']['comments']['picture'][] = $comments_picture_data;
148
					unset($comments_picture_data);
149
				}
150
			}
151
		}
152
153
		if (isset($info['flac']['STREAMINFO'])) {
154
			if (!$this->isDependencyFor('matroska')) {
155
				$info['flac']['compressed_audio_bytes'] = $info['avdataend'] - $info['avdataoffset'];
156
			}
157
			$info['flac']['uncompressed_audio_bytes'] = $info['flac']['STREAMINFO']['samples_stream'] * $info['flac']['STREAMINFO']['channels'] * ($info['flac']['STREAMINFO']['bits_per_sample'] / 8);
158
			if ($info['flac']['uncompressed_audio_bytes'] == 0) {
159
				return $this->error('Corrupt FLAC file: uncompressed_audio_bytes == zero');
160
			}
161
			if (!empty($info['flac']['compressed_audio_bytes'])) {
162
				$info['flac']['compression_ratio'] = $info['flac']['compressed_audio_bytes'] / $info['flac']['uncompressed_audio_bytes'];
163
			}
164
		}
165
166
		// set md5_data_source - built into flac 0.5+
167
		if (isset($info['flac']['STREAMINFO']['audio_signature'])) {
168
169
			if ($info['flac']['STREAMINFO']['audio_signature'] === str_repeat("\x00", 16)) {
170
                $this->warning('FLAC STREAMINFO.audio_signature is null (known issue with libOggFLAC)');
171
			}
172
			else {
173
				$info['md5_data_source'] = '';
174
				$md5 = $info['flac']['STREAMINFO']['audio_signature'];
175
				for ($i = 0; $i < strlen($md5); $i++) {
176
					$info['md5_data_source'] .= str_pad(dechex(ord($md5[$i])), 2, '00', STR_PAD_LEFT);
177
				}
178
				if (!preg_match('/^[0-9a-f]{32}$/', $info['md5_data_source'])) {
179
					unset($info['md5_data_source']);
180
				}
181
			}
182
		}
183
184
		if (isset($info['flac']['STREAMINFO']['bits_per_sample'])) {
185
			$info['audio']['bits_per_sample'] = $info['flac']['STREAMINFO']['bits_per_sample'];
186
			if ($info['audio']['bits_per_sample'] == 8) {
187
				// special case
188
				// must invert sign bit on all data bytes before MD5'ing to match FLAC's calculated value
189
				// MD5sum calculates on unsigned bytes, but FLAC calculated MD5 on 8-bit audio data as signed
190
				$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');
191
			}
192
		}
193
194
		return true;
195
	}
196
197
	private function parseSTREAMINFO($BlockData) {
198
		$info = &$this->getid3->info;
199
200
		$info['flac']['STREAMINFO'] = array();
201
		$streaminfo = &$info['flac']['STREAMINFO'];
202
203
		$streaminfo['min_block_size']  = getid3_lib::BigEndian2Int(substr($BlockData, 0, 2));
204
		$streaminfo['max_block_size']  = getid3_lib::BigEndian2Int(substr($BlockData, 2, 2));
205
		$streaminfo['min_frame_size']  = getid3_lib::BigEndian2Int(substr($BlockData, 4, 3));
206
		$streaminfo['max_frame_size']  = getid3_lib::BigEndian2Int(substr($BlockData, 7, 3));
207
208
		$SRCSBSS                       = getid3_lib::BigEndian2Bin(substr($BlockData, 10, 8));
209
		$streaminfo['sample_rate']     = getid3_lib::Bin2Dec(substr($SRCSBSS,  0, 20));
210
		$streaminfo['channels']        = getid3_lib::Bin2Dec(substr($SRCSBSS, 20,  3)) + 1;
211
		$streaminfo['bits_per_sample'] = getid3_lib::Bin2Dec(substr($SRCSBSS, 23,  5)) + 1;
212
		$streaminfo['samples_stream']  = getid3_lib::Bin2Dec(substr($SRCSBSS, 28, 36));
213
214
		$streaminfo['audio_signature'] = substr($BlockData, 18, 16);
215
216
		if (!empty($streaminfo['sample_rate'])) {
217
218
			$info['audio']['bitrate_mode']    = 'vbr';
219
			$info['audio']['sample_rate']     = $streaminfo['sample_rate'];
220
			$info['audio']['channels']        = $streaminfo['channels'];
221
			$info['audio']['bits_per_sample'] = $streaminfo['bits_per_sample'];
222
			$info['playtime_seconds']         = $streaminfo['samples_stream'] / $streaminfo['sample_rate'];
223
			if ($info['playtime_seconds'] > 0) {
224
				if (!$this->isDependencyFor('matroska')) {
225
					$info['audio']['bitrate'] = (($info['avdataend'] - $info['avdataoffset']) * 8) / $info['playtime_seconds'];
226
				}
227
				else {
228
					$this->warning('Cannot determine audio bitrate because total stream size is unknown');
229
				}
230
			}
231
232
		} else {
233
			return $this->error('Corrupt METAdata block: STREAMINFO');
234
		}
235
236
		return true;
237
	}
238
239
	private function parseAPPLICATION($BlockData) {
240
		$info = &$this->getid3->info;
241
242
		$ApplicationID = getid3_lib::BigEndian2Int(substr($BlockData, 0, 4));
243
		$info['flac']['APPLICATION'][$ApplicationID]['name'] = self::applicationIDLookup($ApplicationID);
244
		$info['flac']['APPLICATION'][$ApplicationID]['data'] = substr($BlockData, 4);
245
246
		return true;
247
	}
248
249
	private function parseSEEKTABLE($BlockData) {
250
		$info = &$this->getid3->info;
251
252
		$offset = 0;
253
		$BlockLength = strlen($BlockData);
254
		$placeholderpattern = str_repeat("\xFF", 8);
255
		while ($offset < $BlockLength) {
256
			$SampleNumberString = substr($BlockData, $offset, 8);
257
			$offset += 8;
258
			if ($SampleNumberString == $placeholderpattern) {
259
260
				// placeholder point
261
				getid3_lib::safe_inc($info['flac']['SEEKTABLE']['placeholders'], 1);
262
				$offset += 10;
263
264
			} else {
265
266
				$SampleNumber                                        = getid3_lib::BigEndian2Int($SampleNumberString);
267
				$info['flac']['SEEKTABLE'][$SampleNumber]['offset']  = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 8));
268
				$offset += 8;
269
				$info['flac']['SEEKTABLE'][$SampleNumber]['samples'] = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 2));
270
				$offset += 2;
271
272
			}
273
		}
274
275
		return true;
276
	}
277
278
	private function parseVORBIS_COMMENT($BlockData) {
279
		$info = &$this->getid3->info;
280
281
		$getid3_ogg = new getid3_ogg($this->getid3);
282
		if ($this->isDependencyFor('matroska')) {
283
			$getid3_ogg->setStringMode($this->data_string);
284
		}
285
		$getid3_ogg->ParseVorbisComments();
286
		if (isset($info['ogg'])) {
287
			unset($info['ogg']['comments_raw']);
288
			$info['flac']['VORBIS_COMMENT'] = $info['ogg'];
289
			unset($info['ogg']);
290
		}
291
292
		unset($getid3_ogg);
293
294
		return true;
295
	}
296
297
	private function parseCUESHEET($BlockData) {
298
		$info = &$this->getid3->info;
299
		$offset = 0;
300
		$info['flac']['CUESHEET']['media_catalog_number'] =                              trim(substr($BlockData, $offset, 128), "\0");
301
		$offset += 128;
302
		$info['flac']['CUESHEET']['lead_in_samples']      =         getid3_lib::BigEndian2Int(substr($BlockData, $offset, 8));
303
		$offset += 8;
304
		$info['flac']['CUESHEET']['flags']['is_cd']       = (bool) (getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1)) & 0x80);
305
		$offset += 1;
306
307
		$offset += 258; // reserved
308
309
		$info['flac']['CUESHEET']['number_tracks']        =         getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1));
310
		$offset += 1;
311
312
		for ($track = 0; $track < $info['flac']['CUESHEET']['number_tracks']; $track++) {
313
			$TrackSampleOffset = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 8));
314
			$offset += 8;
315
			$TrackNumber       = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1));
316
			$offset += 1;
317
318
			$info['flac']['CUESHEET']['tracks'][$TrackNumber]['sample_offset']         = $TrackSampleOffset;
319
320
			$info['flac']['CUESHEET']['tracks'][$TrackNumber]['isrc']                  =                           substr($BlockData, $offset, 12);
321
			$offset += 12;
322
323
			$TrackFlagsRaw                                                             = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1));
324
			$offset += 1;
325
			$info['flac']['CUESHEET']['tracks'][$TrackNumber]['flags']['is_audio']     = (bool) ($TrackFlagsRaw & 0x80);
326
			$info['flac']['CUESHEET']['tracks'][$TrackNumber]['flags']['pre_emphasis'] = (bool) ($TrackFlagsRaw & 0x40);
327
328
			$offset += 13; // reserved
329
330
			$info['flac']['CUESHEET']['tracks'][$TrackNumber]['index_points']          = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1));
331
			$offset += 1;
332
333
			for ($index = 0; $index < $info['flac']['CUESHEET']['tracks'][$TrackNumber]['index_points']; $index++) {
334
				$IndexSampleOffset = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 8));
335
				$offset += 8;
336
				$IndexNumber       = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1));
337
				$offset += 1;
338
339
				$offset += 3; // reserved
340
341
				$info['flac']['CUESHEET']['tracks'][$TrackNumber]['indexes'][$IndexNumber] = $IndexSampleOffset;
342
			}
343
		}
344
345
		return true;
346
	}
347
348
	/**
349
	* Parse METADATA_BLOCK_PICTURE flac structure and extract attachment
350
	* External usage: audio.ogg
351
	*/
352
	public function parsePICTURE() {
353
		$info = &$this->getid3->info;
354
355
		$picture['typeid']         = getid3_lib::BigEndian2Int($this->fread(4));
356
		$picture['picturetype']    = self::pictureTypeLookup($picture['typeid']);
357
		$picture['image_mime']     = $this->fread(getid3_lib::BigEndian2Int($this->fread(4)));
358
		$descr_length              = getid3_lib::BigEndian2Int($this->fread(4));
359
		if ($descr_length) {
360
			$picture['description'] = $this->fread($descr_length);
361
		}
362
		$picture['image_width']    = getid3_lib::BigEndian2Int($this->fread(4));
363
		$picture['image_height']   = getid3_lib::BigEndian2Int($this->fread(4));
364
		$picture['color_depth']    = getid3_lib::BigEndian2Int($this->fread(4));
365
		$picture['colors_indexed'] = getid3_lib::BigEndian2Int($this->fread(4));
366
		$picture['datalength']     = getid3_lib::BigEndian2Int($this->fread(4));
367
368
		if ($picture['image_mime'] == '-->') {
369
			$picture['data'] = $this->fread($picture['datalength']);
370
		} else {
371
			$picture['data'] = $this->saveAttachment(
372
				str_replace('/', '_', $picture['picturetype']).'_'.$this->ftell(),
373
				$this->ftell(),
374
				$picture['datalength'],
375
				$picture['image_mime']);
376
		}
377
378
		$info['flac']['PICTURE'][] = $picture;
379
380
		return true;
381
	}
382
383
	public static function metaBlockTypeLookup($blocktype) {
384
		static $lookup = array(
385
			0 => 'STREAMINFO',
386
			1 => 'PADDING',
387
			2 => 'APPLICATION',
388
			3 => 'SEEKTABLE',
389
			4 => 'VORBIS_COMMENT',
390
			5 => 'CUESHEET',
391
			6 => 'PICTURE',
392
		);
393
		return (isset($lookup[$blocktype]) ? $lookup[$blocktype] : 'reserved');
394
	}
395
396
	public static function applicationIDLookup($applicationid) {
397
		// http://flac.sourceforge.net/id.html
398
		static $lookup = array(
399
			0x41544348 => 'FlacFile',                                                                           // "ATCH"
400
			0x42534F4C => 'beSolo',                                                                             // "BSOL"
401
			0x42554753 => 'Bugs Player',                                                                        // "BUGS"
402
			0x43756573 => 'GoldWave cue points (specification)',                                                // "Cues"
403
			0x46696361 => 'CUE Splitter',                                                                       // "Fica"
404
			0x46746F6C => 'flac-tools',                                                                         // "Ftol"
405
			0x4D4F5442 => 'MOTB MetaCzar',                                                                      // "MOTB"
406
			0x4D505345 => 'MP3 Stream Editor',                                                                  // "MPSE"
407
			0x4D754D4C => 'MusicML: Music Metadata Language',                                                   // "MuML"
408
			0x52494646 => 'Sound Devices RIFF chunk storage',                                                   // "RIFF"
409
			0x5346464C => 'Sound Font FLAC',                                                                    // "SFFL"
410
			0x534F4E59 => 'Sony Creative Software',                                                             // "SONY"
411
			0x5351455A => 'flacsqueeze',                                                                        // "SQEZ"
412
			0x54745776 => 'TwistedWave',                                                                        // "TtWv"
413
			0x55495453 => 'UITS Embedding tools',                                                               // "UITS"
414
			0x61696666 => 'FLAC AIFF chunk storage',                                                            // "aiff"
415
			0x696D6167 => 'flac-image application for storing arbitrary files in APPLICATION metadata blocks',  // "imag"
416
			0x7065656D => 'Parseable Embedded Extensible Metadata (specification)',                             // "peem"
417
			0x71667374 => 'QFLAC Studio',                                                                       // "qfst"
418
			0x72696666 => 'FLAC RIFF chunk storage',                                                            // "riff"
419
			0x74756E65 => 'TagTuner',                                                                           // "tune"
420
			0x78626174 => 'XBAT',                                                                               // "xbat"
421
			0x786D6364 => 'xmcd',                                                                               // "xmcd"
422
		);
423
		return (isset($lookup[$applicationid]) ? $lookup[$applicationid] : 'reserved');
424
	}
425
426
	public static function pictureTypeLookup($type_id) {
427
		static $lookup = array (
428
			 0 => 'Other',
429
			 1 => '32x32 pixels \'file icon\' (PNG only)',
430
			 2 => 'Other file icon',
431
			 3 => 'Cover (front)',
432
			 4 => 'Cover (back)',
433
			 5 => 'Leaflet page',
434
			 6 => 'Media (e.g. label side of CD)',
435
			 7 => 'Lead artist/lead performer/soloist',
436
			 8 => 'Artist/performer',
437
			 9 => 'Conductor',
438
			10 => 'Band/Orchestra',
439
			11 => 'Composer',
440
			12 => 'Lyricist/text writer',
441
			13 => 'Recording Location',
442
			14 => 'During recording',
443
			15 => 'During performance',
444
			16 => 'Movie/video screen capture',
445
			17 => 'A bright coloured fish',
446
			18 => 'Illustration',
447
			19 => 'Band/artist logotype',
448
			20 => 'Publisher/Studio logotype',
449
		);
450
		return (isset($lookup[$type_id]) ? $lookup[$type_id] : 'reserved');
451
	}
452
453
}
454