PageRenderTime 153ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

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

http://github.com/tomahawk-player/tomahawk
C++ | 953 lines | 672 code | 167 blank | 114 comment | 139 complexity | bca1a8e971400d45d4152bbb427d6dcc MD5 | raw file
Possible License(s): LGPL-2.1, BSD-3-Clause, GPL-3.0, GPL-2.0
  1. /*
  2. Copyright 2009 Last.fm Ltd.
  3. Copyright 2009 John Stamp <jstamp@users.sourceforge.net>
  4. Portions Copyright 2003-2005 M. Bakker, Nero AG, http://www.nero.com
  5. - Adapted from main.c found in the FAAD2 source tarball.
  6. This file is part of liblastfm.
  7. liblastfm is free software: you can redistribute it and/or modify
  8. it under the terms of the GNU General Public License as published by
  9. the Free Software Foundation, either version 3 of the License, or
  10. (at your option) any later version.
  11. liblastfm is distributed in the hope that it will be useful,
  12. but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. GNU General Public License for more details.
  15. You should have received a copy of the GNU General Public License
  16. along with liblastfm. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #include "AacSource.h"
  19. #include "AacSource_p.h"
  20. #include <QFile>
  21. #include <algorithm>
  22. #include <cassert>
  23. #include <limits>
  24. #include <iostream>
  25. #include <stdexcept>
  26. #include <errno.h>
  27. #include <string.h>
  28. ////////////////////////////////////////////////////////////////////////
  29. //
  30. // AAC_File
  31. //
  32. ////////////////////////////////////////////////////////////////////////
  33. AAC_File::AAC_File(const QString& fileName, int headerType)
  34. : m_fileName(fileName)
  35. , m_inBuf(NULL)
  36. , m_inBufSize(0)
  37. , m_decoder(0)
  38. , m_overflow(static_cast<unsigned char*>(malloc( sizeof(unsigned char) * 1024 )))
  39. , m_overflowSize(0)
  40. , m_header(headerType)
  41. {
  42. }
  43. AAC_File::~AAC_File()
  44. {
  45. // common
  46. if ( m_decoder )
  47. {
  48. NeAACDecClose( m_decoder );
  49. m_decoder = NULL;
  50. }
  51. if ( m_inBuf )
  52. {
  53. free( m_inBuf );
  54. m_inBufSize = 0;
  55. m_inBuf = NULL;
  56. }
  57. if ( m_overflow )
  58. {
  59. free( m_overflow );
  60. m_overflowSize = 0;
  61. m_overflow = NULL;
  62. }
  63. }
  64. ////////////////////////////////////////////////////////////////////////
  65. //
  66. // AAC with ADTS or ADIF headers
  67. //
  68. ////////////////////////////////////////////////////////////////////////
  69. #define MAX_CHANNELS 6 // Output will get mixed down to 2 channels
  70. #define ADTS_HEADER_SIZE 8
  71. static int adts_sample_rates[] =
  72. {
  73. 96000,
  74. 88200,
  75. 64000,
  76. 48000,
  77. 44100,
  78. 32000,
  79. 24000,
  80. 22050,
  81. 16000,
  82. 12000,
  83. 11025,
  84. 8000,
  85. 7350,
  86. 0,
  87. 0,
  88. 0
  89. };
  90. AAC_ADTS_File::AAC_ADTS_File( const QString& fileName, int headerType ) : AAC_File(fileName, headerType)
  91. , m_file( NULL )
  92. , m_adifSamplerate( 0 )
  93. , m_adifChannels( 0 )
  94. {
  95. }
  96. AAC_ADTS_File::~AAC_ADTS_File()
  97. {
  98. if ( m_file )
  99. {
  100. fclose( m_file );
  101. }
  102. }
  103. void AAC_ADTS_File::fillBuffer( FILE*& fp, unsigned char*& buf, size_t& bufSize, const size_t bytesConsumed )
  104. {
  105. size_t bread;
  106. if ( bytesConsumed > 0 )
  107. {
  108. if ( bufSize )
  109. memmove( (void*)buf, (void*)(buf + bytesConsumed), bufSize*sizeof(unsigned char) );
  110. bread = fread( (void*)(buf + bufSize), 1, bytesConsumed, fp );
  111. bufSize += bread;
  112. if ( bufSize > 3 )
  113. {
  114. if ( memcmp( buf, "TAG", 3 ) == 0 )
  115. bufSize = 0;
  116. }
  117. if ( bufSize > 11 )
  118. {
  119. if ( memcmp( buf, "LYRICSBEGIN", 11 ) == 0 )
  120. bufSize = 0;
  121. }
  122. if ( bufSize > 8 )
  123. {
  124. if ( memcmp( buf, "APETAGEX", 8 ) == 0 )
  125. bufSize = 0;
  126. }
  127. }
  128. }
  129. void AAC_ADTS_File::parse( FILE*& fp, unsigned char*& buf, size_t& bufSize, int &bitrate, double &length )
  130. {
  131. unsigned int frames, frame_length = 0;
  132. int t_framelength = 0;
  133. int samplerate = 0;
  134. double frames_per_sec, bytes_per_frame;
  135. // Read all frames to ensure correct time and bitrate
  136. for ( frames = 0; /* */; frames++ )
  137. {
  138. fillBuffer( fp, buf, bufSize, frame_length );
  139. if ( bufSize > 7 )
  140. {
  141. /* check syncword */
  142. if ( !( (buf[0] == 0xFF) && ((buf[1] & 0xF6) == 0xF0) ) )
  143. break;
  144. if ( frames == 0 )
  145. samplerate = adts_sample_rates[ (buf[2] & 0x3c) >> 2 ];
  146. frame_length = ( ((buf[3] & 0x3) << 11)
  147. | ((buf[4]) << 3)
  148. | (buf[5] >> 5) );
  149. t_framelength += frame_length - ADTS_HEADER_SIZE;
  150. if ( frame_length > bufSize )
  151. break;
  152. bufSize -= frame_length;
  153. }
  154. else
  155. {
  156. break;
  157. }
  158. }
  159. frames_per_sec = samplerate / 1024.0;
  160. if ( frames != 0 )
  161. bytes_per_frame = t_framelength / frames;
  162. else
  163. bytes_per_frame = 0;
  164. bitrate = static_cast<int>(8 * bytes_per_frame * frames_per_sec + 0.5);
  165. if ( frames_per_sec != 0 )
  166. length = frames / frames_per_sec;
  167. else
  168. length = 1;
  169. }
  170. int32_t AAC_ADTS_File::commonSetup( FILE*& fp, NeAACDecHandle& decoder, unsigned char*& buf, size_t& bufSize, uint32_t& samplerate, uint8_t& channels )
  171. {
  172. samplerate = 0;
  173. channels = 0;
  174. fp = fopen(QFile::encodeName(m_fileName), "rb" );
  175. if( !fp )
  176. {
  177. std::cerr << "ERROR: Failed to open " << strerror( errno ) << std::endl;
  178. return -1;
  179. }
  180. if ( !(buf = static_cast<unsigned char*>( malloc(FAAD_MIN_STREAMSIZE*MAX_CHANNELS)) ) )
  181. {
  182. std::cerr << "Memory allocation error" << std::endl;
  183. fclose ( fp );
  184. return -1;
  185. }
  186. memset( buf, 0, FAAD_MIN_STREAMSIZE*MAX_CHANNELS );
  187. bufSize = fread( buf, 1, FAAD_MIN_STREAMSIZE * MAX_CHANNELS, fp );
  188. int tagsize = 0;
  189. if ( !memcmp( buf, "ID3", 3 ) )
  190. {
  191. /* high bit is not used */
  192. tagsize = (buf[6] << 21) | (buf[7] << 14) |
  193. (buf[8] << 7) | (buf[9] << 0);
  194. tagsize += 10;
  195. bufSize -= tagsize;
  196. fillBuffer( fp, buf, bufSize, tagsize );
  197. }
  198. decoder = NeAACDecOpen();
  199. /* Set configuration */
  200. NeAACDecConfigurationPtr config;
  201. config = NeAACDecGetCurrentConfiguration(decoder);
  202. config->outputFormat = FAAD_FMT_16BIT;
  203. config->downMatrix = 1; // Turn 5.1 channels into 2
  204. NeAACDecSetConfiguration( decoder, config);
  205. int32_t initval = 0;
  206. if ((initval = NeAACDecInit(decoder, buf,
  207. FAAD_MIN_STREAMSIZE*MAX_CHANNELS, &samplerate, &channels)) < 0)
  208. {
  209. std::cerr << "Error: could not set up AAC decoder" << std::endl;
  210. if ( buf )
  211. free( buf );
  212. buf = NULL;
  213. NeAACDecClose( decoder );
  214. decoder = NULL;
  215. fclose( fp );
  216. fp = NULL;
  217. }
  218. return initval;
  219. }
  220. bool AAC_ADTS_File::init()
  221. {
  222. uint32_t initSamplerate = 0;
  223. uint8_t initChannels = 0;
  224. int32_t initval = commonSetup( m_file, m_decoder, m_inBuf, m_inBufSize, initSamplerate, initChannels );
  225. if ( initval >= 0 )
  226. {
  227. m_inBufSize -= initval;
  228. fillBuffer( m_file, m_inBuf, m_inBufSize, initval );
  229. // These two only needed for skipping AAC ADIF files
  230. m_adifSamplerate = initSamplerate;
  231. m_adifChannels = initChannels;
  232. return true;
  233. }
  234. throw std::runtime_error( "ERROR: Could not initialize AAC file reader!" );
  235. return false;
  236. }
  237. /*QString AAC_ADTS_File::getMbid()
  238. {
  239. char out[MBID_BUFFER_SIZE];
  240. int const r = getMP3_MBID(QFile::encodeName(m_fileName), out);
  241. if ( r == 0 )
  242. return QString::fromLatin1( out );
  243. return QString();
  244. }*/
  245. void AAC_ADTS_File::getInfo( int& lengthSecs, int& samplerate, int& bitrate, int& nchannels )
  246. {
  247. long fileread;
  248. uint32_t initSamplerate;
  249. uint8_t initChannels;
  250. double initLength = 0;
  251. unsigned char *tempBuf = NULL;
  252. size_t tempBufSize;
  253. FILE *fp = NULL;
  254. NeAACDecHandle decoder = NULL;
  255. commonSetup( fp, decoder, tempBuf, tempBufSize, initSamplerate, initChannels );
  256. long origpos = ftell( fp );
  257. fseek( fp, 0, SEEK_END );
  258. fileread = ftell( fp );
  259. fseek( fp, origpos, SEEK_SET );
  260. if ( (tempBuf[0] == 0xFF) && ((tempBuf[1] & 0xF6) == 0xF0) )
  261. {
  262. parse( fp, tempBuf, tempBufSize, bitrate, initLength );
  263. }
  264. else if (memcmp(tempBuf, "ADIF", 4) == 0)
  265. {
  266. int skip_size = (tempBuf[4] & 0x80) ? 9 : 0;
  267. bitrate = ((tempBuf[4 + skip_size] & 0x0F)<<19) |
  268. (tempBuf[5 + skip_size]<<11) |
  269. (tempBuf[6 + skip_size]<<3) |
  270. (tempBuf[7 + skip_size] & 0xE0);
  271. if ( fileread != 0)
  272. {
  273. initLength = static_cast<double>(fileread) * 8 / bitrate + 0.5;
  274. }
  275. }
  276. lengthSecs = static_cast<int>(initLength);
  277. nchannels = initChannels;
  278. samplerate = initSamplerate;
  279. if ( decoder )
  280. NeAACDecClose( decoder );
  281. if ( fp )
  282. fclose( fp );
  283. if ( tempBuf )
  284. free( tempBuf );
  285. }
  286. void AAC_ADTS_File::skip( const int mSecs )
  287. {
  288. if ( m_header == AAC_ADTS )
  289. {
  290. // As AAC is VBR we need to check all ADTS headers to enable seeking...
  291. // There is no other solution
  292. unsigned char header[8];
  293. unsigned int frameCount, frameLength;
  294. double seconds = 0;
  295. // We need to find the ATDS syncword so rewind to the beginning
  296. // of the unprocessed data.
  297. if ( m_inBufSize > 0 )
  298. {
  299. fseek ( m_file, -m_inBufSize, SEEK_CUR );
  300. m_inBufSize = 0;
  301. }
  302. for( frameCount = 1; seconds * 1000 < mSecs; frameCount++ )
  303. {
  304. if ( fread( header, 1, ADTS_HEADER_SIZE, m_file ) != ADTS_HEADER_SIZE )
  305. {
  306. break;
  307. }
  308. if ( !strncmp( (char*)header, "ID3", 3 ) )
  309. {
  310. // high bit is not used
  311. unsigned char rest[2];
  312. fread( rest, 1, 2, m_file );
  313. int tagsize = (header[6] << 21) | (header[7] << 14) |
  314. (rest[0] << 7) | (rest[1] << 0);
  315. fseek( m_file, tagsize, SEEK_CUR );
  316. fread( header, 1, ADTS_HEADER_SIZE, m_file );
  317. }
  318. if ( !((header[0] == 0xFF) && ((header[1] & 0xF6) == 0xF0)) )
  319. {
  320. std::cerr << "Error: Bad frame header; file may be corrupt!" << std::endl;
  321. break;
  322. }
  323. int samplerate = adts_sample_rates[ (header[2] & 0x3c) >> 2 ];
  324. frameLength = ( ( header[3] & 0x3 ) << 11 )
  325. | ( header[4] << 3 )
  326. | ( header[5] >> 5 );
  327. if ( samplerate > 0 )
  328. seconds += 1024.0 / samplerate;
  329. else
  330. {
  331. std::cerr << "Error: Bad frame header; file may be corrupt!" << std::endl;
  332. break;
  333. }
  334. if ( fseek( m_file, frameLength - ADTS_HEADER_SIZE, SEEK_CUR ) == -1 )
  335. break;
  336. }
  337. m_inBufSize = fread( m_inBuf, 1, FAAD_MIN_STREAMSIZE * MAX_CHANNELS, m_file );
  338. }
  339. else if ( m_header == AAC_ADIF )
  340. {
  341. // AAC ADIF is even worse. There's only the one header at the
  342. // beginning of the file. If you want to skip forward, you have to
  343. // decode block by block and check how far along you are. Lovely, eh?
  344. unsigned long totalSamples = 0;
  345. void *sampleBuffer = NULL;
  346. do
  347. {
  348. NeAACDecFrameInfo frameInfo;
  349. sampleBuffer = NeAACDecDecode(m_decoder, &frameInfo, m_inBuf, static_cast<uint32_t>(m_inBufSize) );
  350. totalSamples += frameInfo.samples;
  351. if ( frameInfo.bytesconsumed > 0 )
  352. {
  353. m_inBufSize -= frameInfo.bytesconsumed;
  354. fillBuffer( m_file, m_inBuf, m_inBufSize, frameInfo.bytesconsumed );
  355. }
  356. if ( totalSamples >= ( mSecs * m_adifSamplerate * m_adifChannels / 1000 ) )
  357. break;
  358. } while ( sampleBuffer != NULL );
  359. }
  360. }
  361. void AAC_ADTS_File::postDecode(unsigned long bytesConsumed)
  362. {
  363. m_inBufSize -= bytesConsumed;
  364. fillBuffer( m_file, m_inBuf, m_inBufSize, bytesConsumed );
  365. }
  366. ////////////////////////////////////////////////////////////////////////
  367. //
  368. // AAC in an MP4 wrapper
  369. //
  370. ////////////////////////////////////////////////////////////////////////
  371. uint32_t read_callback( void *user_data, void *buffer, uint32_t length )
  372. {
  373. return static_cast<uint32_t>(fread( buffer, 1, length, static_cast<FILE*>(user_data) ));
  374. }
  375. uint32_t seek_callback( void *user_data, uint64_t position )
  376. {
  377. return fseek( static_cast<FILE*>(user_data), static_cast<long>(position), SEEK_SET );
  378. }
  379. AAC_MP4_File::AAC_MP4_File( const QString& fileName, int headerType ) : AAC_File(fileName, headerType)
  380. , m_mp4AudioTrack( -1 )
  381. , m_mp4SampleId( 0 )
  382. , m_mp4File ( NULL )
  383. , m_mp4cb ( NULL )
  384. {
  385. }
  386. int32_t AAC_MP4_File::readSample()
  387. {
  388. unsigned int bsize;
  389. int32_t rc = mp4ff_read_sample( m_mp4File, m_mp4AudioTrack, m_mp4SampleId, &m_inBuf, &bsize );
  390. m_inBufSize = bsize;
  391. // Not necessarily an error. Could just mean end of file.
  392. //if ( rc == 0 )
  393. // std::cerr << "Reading samples failed." << std::endl;
  394. return rc;
  395. }
  396. int32_t AAC_MP4_File::getTrack( const mp4ff_t *f )
  397. {
  398. // find AAC track
  399. int32_t numTracks = mp4ff_total_tracks( f );
  400. for ( int32_t i = 0; i < numTracks; i++ )
  401. {
  402. unsigned char *buff = NULL;
  403. unsigned int buff_size = 0;
  404. mp4AudioSpecificConfig mp4ASC;
  405. mp4ff_get_decoder_config( f, i, &buff, &buff_size );
  406. if ( buff )
  407. {
  408. int8_t rc = NeAACDecAudioSpecificConfig( buff, buff_size, &mp4ASC );
  409. free( buff );
  410. if ( rc < 0 )
  411. continue;
  412. return i;
  413. }
  414. }
  415. // can't decode this, probably DRM
  416. return -1;
  417. }
  418. bool AAC_MP4_File::commonSetup( NeAACDecHandle& decoder, mp4ff_callback_t*& cb, FILE*& fp, mp4ff_t*& mp4, int32_t& audioTrack )
  419. {
  420. fp = fopen(QFile::encodeName(m_fileName), "rb");
  421. if ( !fp )
  422. {
  423. throw std::runtime_error( "Error: failed to open AAC file!" );
  424. return false;
  425. }
  426. decoder = NeAACDecOpen();
  427. // Set configuration
  428. NeAACDecConfigurationPtr config;
  429. config = NeAACDecGetCurrentConfiguration( decoder );
  430. config->outputFormat = FAAD_FMT_16BIT;
  431. config->downMatrix = 1; // Turn 5.1 channels into 2
  432. NeAACDecSetConfiguration( decoder, config );
  433. // initialise the callback structure
  434. cb = static_cast<mp4ff_callback_t*>( malloc( sizeof(mp4ff_callback_t) ) );
  435. cb->read = read_callback;
  436. cb->seek = seek_callback;
  437. cb->user_data = fp;
  438. mp4 = mp4ff_open_read( cb );
  439. if ( !mp4 )
  440. {
  441. // unable to open file
  442. free( cb );
  443. cb = NULL;
  444. NeAACDecClose( decoder );
  445. decoder = NULL;
  446. fclose( fp );
  447. fp = NULL;
  448. throw std::runtime_error( "Error: failed to set up AAC decoder!" );
  449. return false;
  450. }
  451. if ( ( audioTrack = getTrack( mp4 )) < 0 )
  452. {
  453. free( cb );
  454. cb = NULL;
  455. NeAACDecClose( decoder );
  456. decoder = NULL;
  457. fclose( fp );
  458. fp = NULL;
  459. mp4ff_close( mp4 );
  460. mp4 = NULL;
  461. audioTrack = 0;
  462. throw std::runtime_error( "Error: Unable to find an audio track. Is the file DRM protected?" );
  463. return false;
  464. }
  465. return true;
  466. }
  467. /*QString AAC_MP4_File::getMbid()
  468. {
  469. int j = mp4ff_meta_get_num_items( m_mp4File );
  470. if ( j > 0 )
  471. {
  472. int k;
  473. for ( k = 0; k < j; k++ )
  474. {
  475. char *tag = NULL, *item = NULL;
  476. if ( mp4ff_meta_get_by_index( m_mp4File, k, &item, &tag ) )
  477. {
  478. if ( item != NULL && tag != NULL )
  479. {
  480. QString key(item);
  481. if ( key.toLower() == "musicbrainz track id" )
  482. {
  483. QString ret(tag);
  484. free( item );
  485. free( tag );
  486. return ret;
  487. }
  488. free( item );
  489. free( tag );
  490. }
  491. }
  492. }
  493. }
  494. return QString();
  495. }*/
  496. void AAC_MP4_File::getInfo( int& lengthSecs, int& samplerate, int& bitrate, int& nchannels )
  497. {
  498. FILE* fp = NULL;
  499. mp4ff_callback_t *cb = NULL;
  500. NeAACDecHandle decoder = NULL;
  501. mp4ff_t* mp4 = NULL;
  502. int32_t audioTrack;
  503. bool success = commonSetup( decoder, cb, fp, mp4, audioTrack );
  504. if ( success )
  505. {
  506. // get basic file info
  507. mp4AudioSpecificConfig mp4ASC;
  508. unsigned char* buffer = NULL;
  509. unsigned int buffer_size = 0;
  510. double f = 1024.0;
  511. unsigned int framesize = 1024;
  512. int32_t samples = mp4ff_num_samples( mp4, audioTrack );
  513. if ( buffer )
  514. {
  515. if ( NeAACDecAudioSpecificConfig(buffer, buffer_size, &mp4ASC) >= 0 )
  516. {
  517. if ( mp4ASC.frameLengthFlag == 1 )
  518. framesize = 960;
  519. if ( mp4ASC.sbr_present_flag == 1 )
  520. framesize *= 2;
  521. if ( mp4ASC.sbr_present_flag == 1 )
  522. f = f * 2.0;
  523. }
  524. free( buffer );
  525. }
  526. samplerate = mp4ff_get_sample_rate( mp4, audioTrack );
  527. if ( samplerate > 0 )
  528. lengthSecs = static_cast<int>(samples * f / samplerate + 0.5);
  529. bitrate = mp4ff_get_avg_bitrate( mp4, audioTrack );
  530. nchannels = mp4ff_get_channel_count( mp4, audioTrack );
  531. mp4ff_close( mp4 );
  532. NeAACDecClose( decoder );
  533. free( cb );
  534. fclose( fp );
  535. }
  536. }
  537. bool AAC_MP4_File::init()
  538. {
  539. FILE* fp = NULL;
  540. bool success = commonSetup( m_decoder, m_mp4cb, fp, m_mp4File, m_mp4AudioTrack );
  541. if ( !success )
  542. return false;
  543. unsigned char* buffer = NULL;
  544. unsigned int buffer_size = 0;
  545. uint32_t samplerate;
  546. uint8_t channels;
  547. mp4ff_get_decoder_config( m_mp4File, m_mp4AudioTrack, &buffer, &buffer_size );
  548. if( NeAACDecInit2( m_decoder, buffer, buffer_size, &samplerate, &channels) < 0 )
  549. {
  550. // If some error initializing occured, skip the file
  551. if ( fp )
  552. fclose( fp );
  553. throw std::runtime_error( "Error: unable to initialize AAC decoder library!" );
  554. return false;
  555. }
  556. if ( buffer )
  557. free( buffer );
  558. return true;
  559. }
  560. void AAC_MP4_File::postDecode(unsigned long)
  561. {
  562. free( m_inBuf );
  563. m_inBuf = NULL;
  564. m_mp4SampleId++;
  565. }
  566. void AAC_MP4_File::skip( const int mSecs )
  567. {
  568. double dur = 0.0;
  569. int f = 1;
  570. unsigned char *buff = NULL;
  571. unsigned int buff_size = 0;
  572. uint32_t totalSamples = mp4ff_num_samples( m_mp4File, m_mp4AudioTrack );
  573. mp4AudioSpecificConfig mp4ASC;
  574. mp4ff_get_decoder_config( m_mp4File, m_mp4AudioTrack, &buff, &buff_size );
  575. if ( buff )
  576. {
  577. int8_t rc = NeAACDecAudioSpecificConfig( buff, buff_size, &mp4ASC );
  578. free( buff );
  579. if ( rc >= 0 && mp4ASC.sbr_present_flag == 1 )
  580. f = 2;
  581. // I think the f multiplier is needed here.
  582. while ( dur * 1000.0 * f / static_cast<double>(mp4ASC.samplingFrequency) < mSecs && m_mp4SampleId < totalSamples )
  583. {
  584. dur += mp4ff_get_sample_duration( m_mp4File, m_mp4AudioTrack, m_mp4SampleId );
  585. m_mp4SampleId++;
  586. }
  587. }
  588. else
  589. std::cerr << "Error: could not skip " << mSecs << " milliseconds" << std::endl;
  590. }
  591. AAC_MP4_File::~AAC_MP4_File()
  592. {
  593. if ( m_mp4File )
  594. mp4ff_close( m_mp4File );
  595. if ( m_mp4cb )
  596. {
  597. free( m_mp4cb );
  598. }
  599. }
  600. ////////////////////////////////////////////////////////////////////////
  601. //
  602. // AacSource
  603. //
  604. ////////////////////////////////////////////////////////////////////////
  605. AacSource::AacSource()
  606. : m_eof( false )
  607. , m_aacFile( NULL )
  608. {}
  609. AacSource::~AacSource()
  610. {
  611. delete m_aacFile;
  612. }
  613. int AacSource::checkHeader()
  614. {
  615. FILE *fp = NULL;
  616. unsigned char header[10];
  617. // check for mp4 file
  618. fp = fopen(QFile::encodeName(m_fileName), "rb");
  619. if ( !fp )
  620. {
  621. std::cerr << "Error: failed to open " << strerror( errno ) << std::endl;
  622. return AAC_File::AAC_UNKNOWN;
  623. }
  624. fread( header, 1, 10, fp );
  625. // MP4 headers
  626. if ( !memcmp( &header[4], "ftyp", 4 ) )
  627. {
  628. fclose( fp );
  629. return AAC_File::AAC_MP4;
  630. }
  631. // Skip id3 tags
  632. int tagsize = 0;
  633. if ( !memcmp( header, "ID3", 3 ) )
  634. {
  635. /* high bit is not used */
  636. tagsize = (header[6] << 21) | (header[7] << 14) |
  637. (header[8] << 7) | (header[9] << 0);
  638. tagsize += 10;
  639. fseek( fp, tagsize, SEEK_SET );
  640. fread( header, 1, 10, fp );
  641. }
  642. // Check for ADTS OR ADIF headers
  643. if ( (header[0] == 0xFF) && ((header[1] & 0xF6) == 0xF0) )
  644. {
  645. fclose( fp );
  646. return AAC_File::AAC_ADTS;
  647. }
  648. else if (memcmp(header, "ADIF", 4) == 0)
  649. {
  650. fclose( fp );
  651. return AAC_File::AAC_ADIF;
  652. }
  653. fclose( fp );
  654. return AAC_File::AAC_UNKNOWN;
  655. }
  656. void AacSource::getInfo( int& lengthSecs, int& samplerate, int& bitrate, int& nchannels )
  657. {
  658. // get the header plus some other stuff..
  659. m_aacFile->getInfo( lengthSecs, samplerate, bitrate, nchannels );
  660. }
  661. void AacSource::init(const QString& fileName)
  662. {
  663. m_fileName = fileName;
  664. int headerType = checkHeader();
  665. if ( headerType != AAC_File::AAC_UNKNOWN )
  666. {
  667. if ( headerType == AAC_File::AAC_MP4 )
  668. m_aacFile = new AAC_MP4_File(m_fileName, headerType);
  669. else
  670. m_aacFile = new AAC_ADTS_File( m_fileName, headerType );
  671. }
  672. if ( m_aacFile )
  673. m_aacFile->init();
  674. else
  675. throw std::runtime_error( "ERROR: No suitable AAC decoder found!" );
  676. }
  677. /*QString AacSource::getMbid()
  678. {
  679. QString mbid = m_aacFile->getMbid();
  680. return mbid;
  681. }*/
  682. void AacSource::skip( const int mSecs )
  683. {
  684. if ( mSecs < 0 || !m_aacFile->m_decoder )
  685. return;
  686. m_aacFile->skip( mSecs );
  687. }
  688. void AacSource::skipSilence(double silenceThreshold /* = 0.0001 */)
  689. {
  690. if ( !m_aacFile->m_decoder )
  691. return;
  692. silenceThreshold *= static_cast<double>( std::numeric_limits<short>::max() );
  693. for (;;)
  694. {
  695. if ( m_aacFile->m_header == AAC_File::AAC_MP4 )
  696. {
  697. if ( !static_cast<AAC_MP4_File*>(m_aacFile)->readSample() )
  698. break;
  699. }
  700. NeAACDecFrameInfo frameInfo;
  701. void* sampleBuffer = NeAACDecDecode(m_aacFile->m_decoder, &frameInfo, m_aacFile->m_inBuf, static_cast<uint32_t>(m_aacFile->m_inBufSize) );
  702. m_aacFile->postDecode( frameInfo.bytesconsumed );
  703. if ( frameInfo.error > 0 )
  704. {
  705. break;
  706. }
  707. else if ( frameInfo.samples > 0 )
  708. {
  709. double sum = 0;
  710. int16_t *buf = static_cast<int16_t*>(sampleBuffer);
  711. switch ( frameInfo.channels )
  712. {
  713. case 1:
  714. for (size_t j = 0; j < frameInfo.samples; ++j)
  715. sum += abs( buf[j] );
  716. break;
  717. case 2:
  718. for (size_t j = 0; j < frameInfo.samples; j+=2)
  719. sum += abs( (buf[j] >> 1) + (buf[j+1] >> 1) );
  720. break;
  721. }
  722. if ( (sum >= silenceThreshold * static_cast<short>(frameInfo.samples/frameInfo.channels) ) )
  723. break;
  724. }
  725. }
  726. }
  727. int AacSource::updateBuffer( signed short *pBuffer, size_t bufferSize )
  728. {
  729. size_t nwrit = 0; //number of samples written to the output buffer
  730. if ( m_aacFile->m_overflowSize > 0 )
  731. {
  732. size_t samples_to_use = bufferSize < m_aacFile->m_overflowSize ? bufferSize : m_aacFile->m_overflowSize;
  733. memcpy( pBuffer, m_aacFile->m_overflow, samples_to_use * sizeof(signed short) );
  734. nwrit += samples_to_use;
  735. m_aacFile->m_overflowSize -= samples_to_use;
  736. memmove( (void*)(m_aacFile->m_overflow), (void*)(m_aacFile->m_overflow + samples_to_use*sizeof(signed short)), samples_to_use*sizeof(signed short) );
  737. }
  738. if ( !m_aacFile->m_decoder )
  739. return 0;
  740. for (;;)
  741. {
  742. signed short* pBufferIt = pBuffer + nwrit;
  743. void* sampleBuffer;
  744. assert( nwrit <= bufferSize );
  745. if ( m_aacFile->m_header == AAC_File::AAC_MP4 )
  746. {
  747. if ( !static_cast<AAC_MP4_File*>(m_aacFile)->readSample() )
  748. {
  749. m_eof = true;
  750. return static_cast<int>(nwrit);
  751. }
  752. }
  753. NeAACDecFrameInfo frameInfo;
  754. sampleBuffer = NeAACDecDecode(m_aacFile->m_decoder, &frameInfo, m_aacFile->m_inBuf, static_cast<uint32_t>(m_aacFile->m_inBufSize) );
  755. size_t samples_to_use = (bufferSize - nwrit) < frameInfo.samples ? bufferSize-nwrit : frameInfo.samples;
  756. if ( samples_to_use > 0 && sampleBuffer != NULL )
  757. {
  758. memcpy( pBufferIt, sampleBuffer, samples_to_use * sizeof(signed short) );
  759. nwrit += samples_to_use;
  760. }
  761. if ( samples_to_use < frameInfo.samples )
  762. {
  763. m_aacFile->m_overflow = static_cast<unsigned char*>(realloc( m_aacFile->m_overflow, (frameInfo.samples - samples_to_use) * sizeof(signed short) ) );
  764. memcpy( m_aacFile->m_overflow, static_cast<signed short*>(sampleBuffer) + samples_to_use, (frameInfo.samples - samples_to_use) * sizeof(signed short) );
  765. m_aacFile->m_overflowSize = frameInfo.samples - samples_to_use;
  766. }
  767. m_aacFile->postDecode( frameInfo.bytesconsumed );
  768. if ( sampleBuffer == NULL )
  769. {
  770. m_eof = true;
  771. break;
  772. }
  773. if ( frameInfo.error > 0 )
  774. {
  775. std::cerr << "Error: " << NeAACDecGetErrorMessage(frameInfo.error) << std::endl;
  776. break;
  777. }
  778. if ( nwrit == bufferSize )
  779. break;
  780. }
  781. return static_cast<int>(nwrit);
  782. }