/thirdparty/liblastfm2/src/fingerprint/contrib/MadSource.cpp

http://github.com/tomahawk-player/tomahawk · C++ · 514 lines · 323 code · 93 blank · 98 comment · 55 complexity · c9e42925f3764bf5e6f8f62e04eb7468 MD5 · raw file

  1. /*
  2. Copyright 2009 Last.fm Ltd.
  3. Copyright 2009 John Stamp <jstamp@users.sourceforge.net>
  4. This file is part of liblastfm.
  5. liblastfm is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation, either version 3 of the License, or
  8. (at your option) any later version.
  9. liblastfm is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with liblastfm. If not, see <http://www.gnu.org/licenses/>.
  15. */
  16. #include <iostream>
  17. #include <fstream>
  18. #include <limits>
  19. #include <climits>
  20. #include <cstdlib>
  21. #include <sstream>
  22. #include <cassert>
  23. #include <stdexcept>
  24. #include "MadSource.h"
  25. #undef max // was definded in mad
  26. using namespace std;
  27. // -----------------------------------------------------------
  28. MadSource::MadSource()
  29. : m_pMP3_Buffer ( new unsigned char[m_MP3_BufferSize+MAD_BUFFER_GUARD] )
  30. {}
  31. // -----------------------------------------------------------
  32. MadSource::~MadSource()
  33. {
  34. if ( m_inputFile.isOpen() )
  35. {
  36. m_inputFile.close();
  37. mad_synth_finish(&m_mad_synth);
  38. mad_frame_finish(&m_mad_frame);
  39. mad_stream_finish(&m_mad_stream);
  40. }
  41. if (m_pMP3_Buffer) delete[] m_pMP3_Buffer;
  42. }
  43. // ---------------------------------------------------------------------
  44. inline short f2s(mad_fixed_t f)
  45. {
  46. /* A fixed point number is formed of the following bit pattern:
  47. *
  48. * SWWWFFFFFFFFFFFFFFFFFFFFFFFFFFFF
  49. * MSB LSB
  50. * S ==> Sign (0 is positive, 1 is negative)
  51. * W ==> Whole part bits
  52. * F ==> Fractional part bits
  53. *
  54. * This pattern contains MAD_F_FRACBITS fractional bits, one
  55. * should alway use this macro when working on the bits of a fixed
  56. * point number. It is not guaranteed to be constant over the
  57. * different platforms supported by libmad.
  58. *
  59. * The signed short value is formed, after clipping, by the least
  60. * significant whole part bit, followed by the 15 most significant
  61. * fractional part bits. Warning: this is a quick and dirty way to
  62. * compute the 16-bit number, madplay includes much better
  63. * algorithms.
  64. */
  65. /* Clipping */
  66. if(f >= MAD_F_ONE)
  67. return(SHRT_MAX);
  68. if(f <= -MAD_F_ONE)
  69. return(-SHRT_MAX);
  70. /* Conversion. */
  71. f = f >> (MAD_F_FRACBITS-15);
  72. return (signed short)f;
  73. }
  74. // ---------------------------------------------------------------------
  75. string MadSource::MadErrorString(const mad_error& error)
  76. {
  77. switch(error)
  78. {
  79. /* Generic unrecoverable errors. */
  80. case MAD_ERROR_BUFLEN:
  81. return("input buffer too small (or EOF)");
  82. case MAD_ERROR_BUFPTR:
  83. return("invalid (null) buffer pointer");
  84. case MAD_ERROR_NOMEM:
  85. return("not enough memory");
  86. /* Frame header related unrecoverable errors. */
  87. case MAD_ERROR_LOSTSYNC:
  88. return("lost synchronization");
  89. case MAD_ERROR_BADLAYER:
  90. return("reserved header layer value");
  91. case MAD_ERROR_BADBITRATE:
  92. return("forbidden bitrate value");
  93. case MAD_ERROR_BADSAMPLERATE:
  94. return("reserved sample frequency value");
  95. case MAD_ERROR_BADEMPHASIS:
  96. return("reserved emphasis value");
  97. /* Recoverable errors */
  98. case MAD_ERROR_BADCRC:
  99. return("CRC check failed");
  100. case MAD_ERROR_BADBITALLOC:
  101. return("forbidden bit allocation value");
  102. case MAD_ERROR_BADSCALEFACTOR:
  103. return("bad scalefactor index");
  104. case MAD_ERROR_BADFRAMELEN:
  105. return("bad frame length");
  106. case MAD_ERROR_BADBIGVALUES:
  107. return("bad big_values count");
  108. case MAD_ERROR_BADBLOCKTYPE:
  109. return("reserved block_type");
  110. case MAD_ERROR_BADSCFSI:
  111. return("bad scalefactor selection info");
  112. case MAD_ERROR_BADDATAPTR:
  113. return("bad main_data_begin pointer");
  114. case MAD_ERROR_BADPART3LEN:
  115. return("bad audio data length");
  116. case MAD_ERROR_BADHUFFTABLE:
  117. return("bad Huffman table select");
  118. case MAD_ERROR_BADHUFFDATA:
  119. return("Huffman data overrun");
  120. case MAD_ERROR_BADSTEREO:
  121. return("incompatible block_type for JS");
  122. /* Unknown error. This switch may be out of sync with libmad's
  123. * defined error codes.
  124. */
  125. default:
  126. return("Unknown error code");
  127. }
  128. }
  129. // -----------------------------------------------------------------------------
  130. bool MadSource::isRecoverable(const mad_error& error, bool log)
  131. {
  132. if (MAD_RECOVERABLE (error))
  133. {
  134. /* Do not print a message if the error is a loss of
  135. * synchronization and this loss is due to the end of
  136. * stream guard bytes. (See the comments marked {3}
  137. * supra for more informations about guard bytes.)
  138. */
  139. if (error != MAD_ERROR_LOSTSYNC /*|| mad_stream.this_frame != pGuard */ && log)
  140. {
  141. cerr << "Recoverable frame level error: "
  142. << MadErrorString(error) << endl;
  143. }
  144. return true;
  145. }
  146. else
  147. {
  148. if (error == MAD_ERROR_BUFLEN)
  149. return true;
  150. else
  151. {
  152. stringstream ss;
  153. ss << "Unrecoverable frame level error: "
  154. << MadErrorString (error) << endl;
  155. throw ss.str();
  156. }
  157. }
  158. return false;
  159. }
  160. // -----------------------------------------------------------
  161. void MadSource::init(const QString& fileName)
  162. {
  163. m_inputFile.setFileName( m_fileName = fileName );
  164. bool fine = m_inputFile.open( QIODevice::ReadOnly );
  165. if ( !fine )
  166. {
  167. throw std::runtime_error ("Cannot load mp3 file!");
  168. }
  169. mad_stream_init(&m_mad_stream);
  170. mad_frame_init (&m_mad_frame);
  171. mad_synth_init (&m_mad_synth);
  172. mad_timer_reset(&m_mad_timer);
  173. m_pcmpos = m_mad_synth.pcm.length;
  174. }
  175. // -----------------------------------------------------------------------------
  176. /*QString MadSource::getMbid()
  177. {
  178. char out[MBID_BUFFER_SIZE];
  179. int const r = getMP3_MBID( QFile::encodeName( m_fileName ), out );
  180. if (r == 0)
  181. return QString::fromLatin1( out );
  182. return QString();
  183. }*/
  184. void MadSource::getInfo(int& lengthSecs, int& samplerate, int& bitrate, int& nchannels )
  185. {
  186. // get the header plus some other stuff..
  187. QFile inputFile(m_fileName);
  188. bool fine = inputFile.open( QIODevice::ReadOnly );
  189. if ( !fine )
  190. {
  191. throw std::runtime_error ("ERROR: Cannot load file for getInfo!");
  192. return;
  193. }
  194. unsigned char* pMP3_Buffer = new unsigned char[m_MP3_BufferSize+MAD_BUFFER_GUARD];
  195. mad_stream madStream;
  196. mad_header madHeader;
  197. mad_timer_t madTimer;
  198. mad_stream_init(&madStream);
  199. mad_timer_reset(&madTimer);
  200. double avgSamplerate = 0;
  201. double avgBitrate = 0;
  202. double avgNChannels = 0;
  203. int nFrames = 0;
  204. while ( fetchData( inputFile, pMP3_Buffer, m_MP3_BufferSize, madStream) )
  205. {
  206. if ( mad_header_decode(&madHeader, &madStream) != 0 )
  207. {
  208. if ( isRecoverable(madStream.error) )
  209. continue;
  210. else
  211. break;
  212. }
  213. mad_timer_add(&madTimer, madHeader.duration);
  214. avgSamplerate += madHeader.samplerate;
  215. avgBitrate += madHeader.bitrate;
  216. if ( madHeader.mode == MAD_MODE_SINGLE_CHANNEL )
  217. ++avgNChannels;
  218. else
  219. avgNChannels += 2;
  220. ++nFrames;
  221. }
  222. inputFile.close();
  223. mad_stream_finish(&madStream);
  224. mad_header_finish(&madHeader);
  225. delete[] pMP3_Buffer;
  226. lengthSecs = static_cast<int>(madTimer.seconds);
  227. samplerate = static_cast<int>( (avgSamplerate/nFrames) + 0.5 );
  228. bitrate = static_cast<int>( (avgBitrate/nFrames) + 0.5 );
  229. nchannels = static_cast<int>( (avgNChannels/nFrames) + 0.5 );
  230. }
  231. // -----------------------------------------------------------
  232. bool MadSource::fetchData( QFile& mp3File,
  233. unsigned char* pMP3_Buffer,
  234. const int MP3_BufferSize,
  235. mad_stream& madStream )
  236. {
  237. unsigned char *pReadStart = NULL;
  238. unsigned char *pGuard = NULL;
  239. if ( madStream.buffer == NULL ||
  240. madStream.error == MAD_ERROR_BUFLEN )
  241. {
  242. size_t readSize;
  243. size_t remaining;
  244. /* {2} libmad may not consume all bytes of the input
  245. * buffer. If the last frame in the buffer is not wholly
  246. * contained by it, then that frame's start is pointed by
  247. * the next_frame member of the Stream structure. This
  248. * common situation occurs when mad_frame_decode() fails,
  249. * sets the stream error code to MAD_ERROR_BUFLEN, and
  250. * sets the next_frame pointer to a non NULL value. (See
  251. * also the comment marked {4} bellow.)
  252. *
  253. * When this occurs, the remaining unused bytes must be
  254. * put back at the beginning of the buffer and taken in
  255. * account before refilling the buffer. This means that
  256. * the input buffer must be large enough to hold a whole
  257. * frame at the highest observable bit-rate (currently 448
  258. * kb/s). XXX=XXX Is 2016 bytes the size of the largest
  259. * frame? (448000*(1152/32000))/8
  260. */
  261. if (madStream.next_frame != NULL)
  262. {
  263. remaining = madStream.bufend - madStream.next_frame;
  264. memmove (pMP3_Buffer, madStream.next_frame, remaining);
  265. pReadStart = pMP3_Buffer + remaining;
  266. readSize = MP3_BufferSize - remaining;
  267. }
  268. else
  269. {
  270. readSize = MP3_BufferSize;
  271. pReadStart = pMP3_Buffer;
  272. remaining = 0;
  273. }
  274. readSize = mp3File.read( reinterpret_cast<char*>(pReadStart), readSize );
  275. // nothing else to read!
  276. if (readSize <= 0)
  277. return false;
  278. if ( mp3File.atEnd() )
  279. {
  280. pGuard = pReadStart + readSize;
  281. memset (pGuard, 0, MAD_BUFFER_GUARD);
  282. readSize += MAD_BUFFER_GUARD;
  283. }
  284. // Pipe the new buffer content to libmad's stream decoder facility.
  285. mad_stream_buffer( &madStream, pMP3_Buffer,
  286. static_cast<unsigned int>(readSize + remaining));
  287. madStream.error = MAD_ERROR_NONE;
  288. }
  289. return true;
  290. }
  291. // -----------------------------------------------------------------------------
  292. void MadSource::skipSilence(double silenceThreshold /* = 0.0001 */)
  293. {
  294. mad_frame madFrame;
  295. mad_synth madSynth;
  296. mad_frame_init(&madFrame);
  297. mad_synth_init (&madSynth);
  298. silenceThreshold *= static_cast<double>( numeric_limits<short>::max() );
  299. for (;;)
  300. {
  301. if ( !fetchData( m_inputFile, m_pMP3_Buffer, m_MP3_BufferSize, m_mad_stream) )
  302. break;
  303. if ( mad_frame_decode(&madFrame, &m_mad_stream) != 0 )
  304. {
  305. if ( isRecoverable(m_mad_stream.error) )
  306. continue;
  307. else
  308. break;
  309. }
  310. mad_synth_frame (&madSynth, &madFrame);
  311. double sum = 0;
  312. switch (madSynth.pcm.channels)
  313. {
  314. case 1:
  315. for (size_t j = 0; j < madSynth.pcm.length; ++j)
  316. sum += abs(f2s(madSynth.pcm.samples[0][j]));
  317. break;
  318. case 2:
  319. for (size_t j = 0; j < madSynth.pcm.length; ++j)
  320. sum += abs(f2s(
  321. (madSynth.pcm.samples[0][j] >> 1)
  322. + (madSynth.pcm.samples[1][j] >> 1)));
  323. break;
  324. }
  325. if ( (sum >= silenceThreshold * madSynth.pcm.length) )
  326. break;
  327. }
  328. mad_frame_finish(&madFrame);
  329. }
  330. // -----------------------------------------------------------------------------
  331. void MadSource::skip(const int mSecs)
  332. {
  333. if ( mSecs <= 0 )
  334. return;
  335. mad_header madHeader;
  336. mad_header_init(&madHeader);
  337. for (;;)
  338. {
  339. if (!fetchData( m_inputFile, m_pMP3_Buffer, m_MP3_BufferSize, m_mad_stream))
  340. break;
  341. if ( mad_header_decode(&madHeader, &m_mad_stream) != 0 )
  342. {
  343. if ( isRecoverable(m_mad_stream.error) )
  344. continue;
  345. else
  346. break;
  347. }
  348. mad_timer_add(&m_mad_timer, madHeader.duration);
  349. if ( mad_timer_count(m_mad_timer, MAD_UNITS_MILLISECONDS) >= mSecs )
  350. break;
  351. }
  352. mad_header_finish(&madHeader);
  353. }
  354. // -----------------------------------------------------------
  355. int MadSource::updateBuffer(signed short* pBuffer, size_t bufferSize)
  356. {
  357. size_t nwrit = 0; //number of samples written to the output buffer
  358. for (;;)
  359. {
  360. // get a (valid) frame
  361. // m_pcmpos == 0 could mean two things
  362. // - we have completely decoded a frame, but the output buffer is still
  363. // not full (it would make more sense for pcmpos == pcm.length(), but
  364. // the loop assigns pcmpos = 0 at the end and does it this way!
  365. // - we are starting a stream
  366. if ( m_pcmpos == m_mad_synth.pcm.length )
  367. {
  368. if ( !fetchData( m_inputFile, m_pMP3_Buffer, m_MP3_BufferSize, m_mad_stream) )
  369. {
  370. break; // nothing else to read
  371. }
  372. // decode the frame
  373. if (mad_frame_decode (&m_mad_frame, &m_mad_stream))
  374. {
  375. if ( isRecoverable(m_mad_stream.error) )
  376. continue;
  377. else
  378. break;
  379. } // if (mad_frame_decode (&madFrame, &madStream))
  380. mad_timer_add (&m_mad_timer, m_mad_frame.header.duration);
  381. mad_synth_frame (&m_mad_synth, &m_mad_frame);
  382. m_pcmpos = 0;
  383. }
  384. size_t samples_for_mp3 = m_mad_synth.pcm.length - m_pcmpos;
  385. size_t samples_for_buf = bufferSize - nwrit;
  386. signed short* pBufferIt = pBuffer + nwrit;
  387. size_t i = 0, j = 0;
  388. switch( m_mad_synth.pcm.channels )
  389. {
  390. case 1:
  391. {
  392. size_t samples_to_use = min (samples_for_mp3, samples_for_buf);
  393. for (i = 0; i < samples_to_use; ++i )
  394. pBufferIt[i] = f2s( m_mad_synth.pcm.samples[0][i+m_pcmpos] );
  395. }
  396. j = i;
  397. break;
  398. case 2:
  399. for (; i < samples_for_mp3 && j < samples_for_buf ; ++i, j+=2 )
  400. {
  401. pBufferIt[j] = f2s( m_mad_synth.pcm.samples[0][i+m_pcmpos] );
  402. pBufferIt[j+1] = f2s( m_mad_synth.pcm.samples[1][i+m_pcmpos] );
  403. }
  404. break;
  405. default:
  406. cerr << "wtf kind of mp3 has " << m_mad_synth.pcm.channels << " channels??\n";
  407. break;
  408. }
  409. m_pcmpos += i;
  410. nwrit += j;
  411. assert( nwrit <= bufferSize );
  412. if (nwrit == bufferSize)
  413. return static_cast<int>(nwrit);
  414. }
  415. return static_cast<int>(nwrit);
  416. }
  417. // -----------------------------------------------------------------------------