PageRenderTime 28ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/ID3/module.audio.flac.php

https://gitlab.com/Gashler/dp
PHP | 442 lines | 342 code | 71 blank | 29 comment | 49 complexity | bcedd6489fb8e0d5c15cc30397a0d28b MD5 | raw file
  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. getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.audio.ogg.php', __FILE__, true);
  16. /**
  17. * @tutorial http://flac.sourceforge.net/format.html
  18. */
  19. class getid3_flac extends getid3_handler
  20. {
  21. const syncword = 'fLaC';
  22. public function Analyze() {
  23. $info = &$this->getid3->info;
  24. $this->fseek($info['avdataoffset']);
  25. $StreamMarker = $this->fread(4);
  26. if ($StreamMarker != self::syncword) {
  27. return $this->error('Expecting "'.getid3_lib::PrintHexBytes(self::syncword).'" at offset '.$info['avdataoffset'].', found "'.getid3_lib::PrintHexBytes($StreamMarker).'"');
  28. }
  29. $info['fileformat'] = 'flac';
  30. $info['audio']['dataformat'] = 'flac';
  31. $info['audio']['bitrate_mode'] = 'vbr';
  32. $info['audio']['lossless'] = true;
  33. // parse flac container
  34. return $this->parseMETAdata();
  35. }
  36. public function parseMETAdata() {
  37. $info = &$this->getid3->info;
  38. do {
  39. $BlockOffset = $this->ftell();
  40. $BlockHeader = $this->fread(4);
  41. $LBFBT = getid3_lib::BigEndian2Int(substr($BlockHeader, 0, 1));
  42. $LastBlockFlag = (bool) ($LBFBT & 0x80);
  43. $BlockType = ($LBFBT & 0x7F);
  44. $BlockLength = getid3_lib::BigEndian2Int(substr($BlockHeader, 1, 3));
  45. $BlockTypeText = self::metaBlockTypeLookup($BlockType);
  46. if (($BlockOffset + 4 + $BlockLength) > $info['avdataend']) {
  47. $this->error('METADATA_BLOCK_HEADER.BLOCK_TYPE ('.$BlockTypeText.') at offset '.$BlockOffset.' extends beyond end of file');
  48. break;
  49. }
  50. if ($BlockLength < 1) {
  51. $this->error('METADATA_BLOCK_HEADER.BLOCK_LENGTH ('.$BlockLength.') at offset '.$BlockOffset.' is invalid');
  52. break;
  53. }
  54. $info['flac'][$BlockTypeText]['raw'] = array();
  55. $BlockTypeText_raw = &$info['flac'][$BlockTypeText]['raw'];
  56. $BlockTypeText_raw['offset'] = $BlockOffset;
  57. $BlockTypeText_raw['last_meta_block'] = $LastBlockFlag;
  58. $BlockTypeText_raw['block_type'] = $BlockType;
  59. $BlockTypeText_raw['block_type_text'] = $BlockTypeText;
  60. $BlockTypeText_raw['block_length'] = $BlockLength;
  61. if ($BlockTypeText_raw['block_type'] != 0x06) { // do not read attachment data automatically
  62. $BlockTypeText_raw['block_data'] = $this->fread($BlockLength);
  63. }
  64. switch ($BlockTypeText) {
  65. case 'STREAMINFO': // 0x00
  66. if (!$this->parseSTREAMINFO($BlockTypeText_raw['block_data'])) {
  67. return false;
  68. }
  69. break;
  70. case 'PADDING': // 0x01
  71. unset($info['flac']['PADDING']); // ignore
  72. break;
  73. case 'APPLICATION': // 0x02
  74. if (!$this->parseAPPLICATION($BlockTypeText_raw['block_data'])) {
  75. return false;
  76. }
  77. break;
  78. case 'SEEKTABLE': // 0x03
  79. if (!$this->parseSEEKTABLE($BlockTypeText_raw['block_data'])) {
  80. return false;
  81. }
  82. break;
  83. case 'VORBIS_COMMENT': // 0x04
  84. if (!$this->parseVORBIS_COMMENT($BlockTypeText_raw['block_data'])) {
  85. return false;
  86. }
  87. break;
  88. case 'CUESHEET': // 0x05
  89. if (!$this->parseCUESHEET($BlockTypeText_raw['block_data'])) {
  90. return false;
  91. }
  92. break;
  93. case 'PICTURE': // 0x06
  94. if (!$this->parsePICTURE()) {
  95. return false;
  96. }
  97. break;
  98. default:
  99. $this->warning('Unhandled METADATA_BLOCK_HEADER.BLOCK_TYPE ('.$BlockType.') at offset '.$BlockOffset);
  100. }
  101. unset($info['flac'][$BlockTypeText]['raw']);
  102. $info['avdataoffset'] = $this->ftell();
  103. }
  104. while ($LastBlockFlag === false);
  105. // handle tags
  106. if (!empty($info['flac']['VORBIS_COMMENT']['comments'])) {
  107. $info['flac']['comments'] = $info['flac']['VORBIS_COMMENT']['comments'];
  108. }
  109. if (!empty($info['flac']['VORBIS_COMMENT']['vendor'])) {
  110. $info['audio']['encoder'] = str_replace('reference ', '', $info['flac']['VORBIS_COMMENT']['vendor']);
  111. }
  112. // copy attachments to 'comments' array if nesesary
  113. if (isset($info['flac']['PICTURE']) && ($this->getid3->option_save_attachments !== getID3::ATTACHMENTS_NONE)) {
  114. foreach ($info['flac']['PICTURE'] as $entry) {
  115. if (!empty($entry['data'])) {
  116. $info['flac']['comments']['picture'][] = array('image_mime'=>$entry['image_mime'], 'data'=>$entry['data']);
  117. }
  118. }
  119. }
  120. if (isset($info['flac']['STREAMINFO'])) {
  121. if (!$this->isDependencyFor('matroska')) {
  122. $info['flac']['compressed_audio_bytes'] = $info['avdataend'] - $info['avdataoffset'];
  123. }
  124. $info['flac']['uncompressed_audio_bytes'] = $info['flac']['STREAMINFO']['samples_stream'] * $info['flac']['STREAMINFO']['channels'] * ($info['flac']['STREAMINFO']['bits_per_sample'] / 8);
  125. if ($info['flac']['uncompressed_audio_bytes'] == 0) {
  126. return $this->error('Corrupt FLAC file: uncompressed_audio_bytes == zero');
  127. }
  128. if (!empty($info['flac']['compressed_audio_bytes'])) {
  129. $info['flac']['compression_ratio'] = $info['flac']['compressed_audio_bytes'] / $info['flac']['uncompressed_audio_bytes'];
  130. }
  131. }
  132. // set md5_data_source - built into flac 0.5+
  133. if (isset($info['flac']['STREAMINFO']['audio_signature'])) {
  134. if ($info['flac']['STREAMINFO']['audio_signature'] === str_repeat("\x00", 16)) {
  135. $this->warning('FLAC STREAMINFO.audio_signature is null (known issue with libOggFLAC)');
  136. }
  137. else {
  138. $info['md5_data_source'] = '';
  139. $md5 = $info['flac']['STREAMINFO']['audio_signature'];
  140. for ($i = 0; $i < strlen($md5); $i++) {
  141. $info['md5_data_source'] .= str_pad(dechex(ord($md5[$i])), 2, '00', STR_PAD_LEFT);
  142. }
  143. if (!preg_match('/^[0-9a-f]{32}$/', $info['md5_data_source'])) {
  144. unset($info['md5_data_source']);
  145. }
  146. }
  147. }
  148. if (isset($info['flac']['STREAMINFO']['bits_per_sample'])) {
  149. $info['audio']['bits_per_sample'] = $info['flac']['STREAMINFO']['bits_per_sample'];
  150. if ($info['audio']['bits_per_sample'] == 8) {
  151. // special case
  152. // must invert sign bit on all data bytes before MD5'ing to match FLAC's calculated value
  153. // MD5sum calculates on unsigned bytes, but FLAC calculated MD5 on 8-bit audio data as signed
  154. $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');
  155. }
  156. }
  157. return true;
  158. }
  159. private function parseSTREAMINFO($BlockData) {
  160. $info = &$this->getid3->info;
  161. $info['flac']['STREAMINFO'] = array();
  162. $streaminfo = &$info['flac']['STREAMINFO'];
  163. $streaminfo['min_block_size'] = getid3_lib::BigEndian2Int(substr($BlockData, 0, 2));
  164. $streaminfo['max_block_size'] = getid3_lib::BigEndian2Int(substr($BlockData, 2, 2));
  165. $streaminfo['min_frame_size'] = getid3_lib::BigEndian2Int(substr($BlockData, 4, 3));
  166. $streaminfo['max_frame_size'] = getid3_lib::BigEndian2Int(substr($BlockData, 7, 3));
  167. $SRCSBSS = getid3_lib::BigEndian2Bin(substr($BlockData, 10, 8));
  168. $streaminfo['sample_rate'] = getid3_lib::Bin2Dec(substr($SRCSBSS, 0, 20));
  169. $streaminfo['channels'] = getid3_lib::Bin2Dec(substr($SRCSBSS, 20, 3)) + 1;
  170. $streaminfo['bits_per_sample'] = getid3_lib::Bin2Dec(substr($SRCSBSS, 23, 5)) + 1;
  171. $streaminfo['samples_stream'] = getid3_lib::Bin2Dec(substr($SRCSBSS, 28, 36));
  172. $streaminfo['audio_signature'] = substr($BlockData, 18, 16);
  173. if (!empty($streaminfo['sample_rate'])) {
  174. $info['audio']['bitrate_mode'] = 'vbr';
  175. $info['audio']['sample_rate'] = $streaminfo['sample_rate'];
  176. $info['audio']['channels'] = $streaminfo['channels'];
  177. $info['audio']['bits_per_sample'] = $streaminfo['bits_per_sample'];
  178. $info['playtime_seconds'] = $streaminfo['samples_stream'] / $streaminfo['sample_rate'];
  179. if ($info['playtime_seconds'] > 0) {
  180. if (!$this->isDependencyFor('matroska')) {
  181. $info['audio']['bitrate'] = (($info['avdataend'] - $info['avdataoffset']) * 8) / $info['playtime_seconds'];
  182. }
  183. else {
  184. $this->warning('Cannot determine audio bitrate because total stream size is unknown');
  185. }
  186. }
  187. } else {
  188. return $this->error('Corrupt METAdata block: STREAMINFO');
  189. }
  190. return true;
  191. }
  192. private function parseAPPLICATION($BlockData) {
  193. $info = &$this->getid3->info;
  194. $ApplicationID = getid3_lib::BigEndian2Int(substr($BlockData, 0, 4));
  195. $info['flac']['APPLICATION'][$ApplicationID]['name'] = self::applicationIDLookup($ApplicationID);
  196. $info['flac']['APPLICATION'][$ApplicationID]['data'] = substr($BlockData, 4);
  197. return true;
  198. }
  199. private function parseSEEKTABLE($BlockData) {
  200. $info = &$this->getid3->info;
  201. $offset = 0;
  202. $BlockLength = strlen($BlockData);
  203. $placeholderpattern = str_repeat("\xFF", 8);
  204. while ($offset < $BlockLength) {
  205. $SampleNumberString = substr($BlockData, $offset, 8);
  206. $offset += 8;
  207. if ($SampleNumberString == $placeholderpattern) {
  208. // placeholder point
  209. getid3_lib::safe_inc($info['flac']['SEEKTABLE']['placeholders'], 1);
  210. $offset += 10;
  211. } else {
  212. $SampleNumber = getid3_lib::BigEndian2Int($SampleNumberString);
  213. $info['flac']['SEEKTABLE'][$SampleNumber]['offset'] = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 8));
  214. $offset += 8;
  215. $info['flac']['SEEKTABLE'][$SampleNumber]['samples'] = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 2));
  216. $offset += 2;
  217. }
  218. }
  219. return true;
  220. }
  221. private function parseVORBIS_COMMENT($BlockData) {
  222. $info = &$this->getid3->info;
  223. $getid3_ogg = new getid3_ogg($this->getid3);
  224. if ($this->isDependencyFor('matroska')) {
  225. $getid3_ogg->setStringMode($this->data_string);
  226. }
  227. $getid3_ogg->ParseVorbisComments();
  228. if (isset($info['ogg'])) {
  229. unset($info['ogg']['comments_raw']);
  230. $info['flac']['VORBIS_COMMENT'] = $info['ogg'];
  231. unset($info['ogg']);
  232. }
  233. unset($getid3_ogg);
  234. return true;
  235. }
  236. private function parseCUESHEET($BlockData) {
  237. $info = &$this->getid3->info;
  238. $offset = 0;
  239. $info['flac']['CUESHEET']['media_catalog_number'] = trim(substr($BlockData, $offset, 128), "\0");
  240. $offset += 128;
  241. $info['flac']['CUESHEET']['lead_in_samples'] = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 8));
  242. $offset += 8;
  243. $info['flac']['CUESHEET']['flags']['is_cd'] = (bool) (getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1)) & 0x80);
  244. $offset += 1;
  245. $offset += 258; // reserved
  246. $info['flac']['CUESHEET']['number_tracks'] = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1));
  247. $offset += 1;
  248. for ($track = 0; $track < $info['flac']['CUESHEET']['number_tracks']; $track++) {
  249. $TrackSampleOffset = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 8));
  250. $offset += 8;
  251. $TrackNumber = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1));
  252. $offset += 1;
  253. $info['flac']['CUESHEET']['tracks'][$TrackNumber]['sample_offset'] = $TrackSampleOffset;
  254. $info['flac']['CUESHEET']['tracks'][$TrackNumber]['isrc'] = substr($BlockData, $offset, 12);
  255. $offset += 12;
  256. $TrackFlagsRaw = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1));
  257. $offset += 1;
  258. $info['flac']['CUESHEET']['tracks'][$TrackNumber]['flags']['is_audio'] = (bool) ($TrackFlagsRaw & 0x80);
  259. $info['flac']['CUESHEET']['tracks'][$TrackNumber]['flags']['pre_emphasis'] = (bool) ($TrackFlagsRaw & 0x40);
  260. $offset += 13; // reserved
  261. $info['flac']['CUESHEET']['tracks'][$TrackNumber]['index_points'] = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1));
  262. $offset += 1;
  263. for ($index = 0; $index < $info['flac']['CUESHEET']['tracks'][$TrackNumber]['index_points']; $index++) {
  264. $IndexSampleOffset = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 8));
  265. $offset += 8;
  266. $IndexNumber = getid3_lib::BigEndian2Int(substr($BlockData, $offset, 1));
  267. $offset += 1;
  268. $offset += 3; // reserved
  269. $info['flac']['CUESHEET']['tracks'][$TrackNumber]['indexes'][$IndexNumber] = $IndexSampleOffset;
  270. }
  271. }
  272. return true;
  273. }
  274. /**
  275. * Parse METADATA_BLOCK_PICTURE flac structure and extract attachment
  276. * External usage: audio.ogg
  277. */
  278. public function parsePICTURE() {
  279. $info = &$this->getid3->info;
  280. $picture['typeid'] = getid3_lib::BigEndian2Int($this->fread(4));
  281. $picture['type'] = self::pictureTypeLookup($picture['typeid']);
  282. $picture['image_mime'] = $this->fread(getid3_lib::BigEndian2Int($this->fread(4)));
  283. $descr_length = getid3_lib::BigEndian2Int($this->fread(4));
  284. if ($descr_length) {
  285. $picture['description'] = $this->fread($descr_length);
  286. }
  287. $picture['width'] = getid3_lib::BigEndian2Int($this->fread(4));
  288. $picture['height'] = getid3_lib::BigEndian2Int($this->fread(4));
  289. $picture['color_depth'] = getid3_lib::BigEndian2Int($this->fread(4));
  290. $picture['colors_indexed'] = getid3_lib::BigEndian2Int($this->fread(4));
  291. $data_length = getid3_lib::BigEndian2Int($this->fread(4));
  292. if ($picture['image_mime'] == '-->') {
  293. $picture['data'] = $this->fread($data_length);
  294. } else {
  295. $picture['data'] = $this->saveAttachment(
  296. str_replace('/', '_', $picture['type']).'_'.$this->ftell(),
  297. $this->ftell(),
  298. $data_length,
  299. $picture['image_mime']);
  300. }
  301. $info['flac']['PICTURE'][] = $picture;
  302. return true;
  303. }
  304. public static function metaBlockTypeLookup($blocktype) {
  305. static $lookup = array(
  306. 0 => 'STREAMINFO',
  307. 1 => 'PADDING',
  308. 2 => 'APPLICATION',
  309. 3 => 'SEEKTABLE',
  310. 4 => 'VORBIS_COMMENT',
  311. 5 => 'CUESHEET',
  312. 6 => 'PICTURE',
  313. );
  314. return (isset($lookup[$blocktype]) ? $lookup[$blocktype] : 'reserved');
  315. }
  316. public static function applicationIDLookup($applicationid) {
  317. // http://flac.sourceforge.net/id.html
  318. static $lookup = array(
  319. 0x41544348 => 'FlacFile', // "ATCH"
  320. 0x42534F4C => 'beSolo', // "BSOL"
  321. 0x42554753 => 'Bugs Player', // "BUGS"
  322. 0x43756573 => 'GoldWave cue points (specification)', // "Cues"
  323. 0x46696361 => 'CUE Splitter', // "Fica"
  324. 0x46746F6C => 'flac-tools', // "Ftol"
  325. 0x4D4F5442 => 'MOTB MetaCzar', // "MOTB"
  326. 0x4D505345 => 'MP3 Stream Editor', // "MPSE"
  327. 0x4D754D4C => 'MusicML: Music Metadata Language', // "MuML"
  328. 0x52494646 => 'Sound Devices RIFF chunk storage', // "RIFF"
  329. 0x5346464C => 'Sound Font FLAC', // "SFFL"
  330. 0x534F4E59 => 'Sony Creative Software', // "SONY"
  331. 0x5351455A => 'flacsqueeze', // "SQEZ"
  332. 0x54745776 => 'TwistedWave', // "TtWv"
  333. 0x55495453 => 'UITS Embedding tools', // "UITS"
  334. 0x61696666 => 'FLAC AIFF chunk storage', // "aiff"
  335. 0x696D6167 => 'flac-image application for storing arbitrary files in APPLICATION metadata blocks', // "imag"
  336. 0x7065656D => 'Parseable Embedded Extensible Metadata (specification)', // "peem"
  337. 0x71667374 => 'QFLAC Studio', // "qfst"
  338. 0x72696666 => 'FLAC RIFF chunk storage', // "riff"
  339. 0x74756E65 => 'TagTuner', // "tune"
  340. 0x78626174 => 'XBAT', // "xbat"
  341. 0x786D6364 => 'xmcd', // "xmcd"
  342. );
  343. return (isset($lookup[$applicationid]) ? $lookup[$applicationid] : 'reserved');
  344. }
  345. public static function pictureTypeLookup($type_id) {
  346. static $lookup = array (
  347. 0 => 'Other',
  348. 1 => '32x32 pixels \'file icon\' (PNG only)',
  349. 2 => 'Other file icon',
  350. 3 => 'Cover (front)',
  351. 4 => 'Cover (back)',
  352. 5 => 'Leaflet page',
  353. 6 => 'Media (e.g. label side of CD)',
  354. 7 => 'Lead artist/lead performer/soloist',
  355. 8 => 'Artist/performer',
  356. 9 => 'Conductor',
  357. 10 => 'Band/Orchestra',
  358. 11 => 'Composer',
  359. 12 => 'Lyricist/text writer',
  360. 13 => 'Recording Location',
  361. 14 => 'During recording',
  362. 15 => 'During performance',
  363. 16 => 'Movie/video screen capture',
  364. 17 => 'A bright coloured fish',
  365. 18 => 'Illustration',
  366. 19 => 'Band/artist logotype',
  367. 20 => 'Publisher/Studio logotype',
  368. );
  369. return (isset($lookup[$type_id]) ? $lookup[$type_id] : 'reserved');
  370. }
  371. }