replaygain.c
上传用户:wstnjxml
上传日期:2014-04-03
资源大小:7248k
文件大小:18k
源码类别:

Windows CE

开发平台:

C/C++

  1. /* grabbag - Convenience lib for various routines common to several tools
  2.  * Copyright (C) 2002,2003,2004,2005  Josh Coalson
  3.  *
  4.  * This program is free software; you can redistribute it and/or
  5.  * modify it under the terms of the GNU General Public License
  6.  * as published by the Free Software Foundation; either version 2
  7.  * of the License, or (at your option) any later version.
  8.  *
  9.  * This program 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.  *
  14.  * You should have received a copy of the GNU General Public License
  15.  * along with this program; if not, write to the Free Software
  16.  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
  17.  */
  18. #include "share/grabbag.h"
  19. #include "share/replaygain_analysis.h"
  20. #include "FLAC/assert.h"
  21. #include "FLAC/file_decoder.h"
  22. #include "FLAC/metadata.h"
  23. #include <locale.h>
  24. #include <math.h>
  25. #include <stdio.h>
  26. #include <stdlib.h>
  27. #include <string.h>
  28. #if defined _MSC_VER || defined __MINGW32__
  29. #include <io.h> /* for chmod() */
  30. #endif
  31. #include <sys/stat.h> /* for stat(), maybe chmod() */
  32. #ifdef local_min
  33. #undef local_min
  34. #endif
  35. #define local_min(a,b) ((a)<(b)?(a):(b))
  36. #ifdef local_max
  37. #undef local_max
  38. #endif
  39. #define local_max(a,b) ((a)>(b)?(a):(b))
  40. static const FLAC__byte *tag_title_gain_ = "REPLAYGAIN_TRACK_GAIN";
  41. static const FLAC__byte *tag_title_peak_ = "REPLAYGAIN_TRACK_PEAK";
  42. static const FLAC__byte *tag_album_gain_ = "REPLAYGAIN_ALBUM_GAIN";
  43. static const FLAC__byte *tag_album_peak_ = "REPLAYGAIN_ALBUM_PEAK";
  44. static const char *peak_format_ = "%s=%1.8f";
  45. static const char *gain_format_ = "%s=%+2.2f dB";
  46. static double album_peak_, title_peak_;
  47. const unsigned GRABBAG__REPLAYGAIN_MAX_TAG_SPACE_REQUIRED = 148;
  48. /*
  49. FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 21 + 1 + 10 +
  50. FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 21 + 1 + 12 +
  51. FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 21 + 1 + 10 +
  52. FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 21 + 1 + 12
  53. */
  54. static FLAC__bool get_file_stats_(const char *filename, struct stat *stats)
  55. {
  56. FLAC__ASSERT(0 != filename);
  57. FLAC__ASSERT(0 != stats);
  58. return (0 == stat(filename, stats));
  59. }
  60. static void set_file_stats_(const char *filename, struct stat *stats)
  61. {
  62. FLAC__ASSERT(0 != filename);
  63. FLAC__ASSERT(0 != stats);
  64. (void)chmod(filename, stats->st_mode);
  65. }
  66. static FLAC__bool append_tag_(FLAC__StreamMetadata *block, const char *format, const FLAC__byte *name, float value)
  67. {
  68. char buffer[256];
  69. char *saved_locale;
  70. FLAC__StreamMetadata_VorbisComment_Entry entry;
  71. FLAC__ASSERT(0 != block);
  72. FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
  73. FLAC__ASSERT(0 != name);
  74. FLAC__ASSERT(0 != value);
  75. buffer[sizeof(buffer)-1] = '';
  76. /*
  77.  * We need to save the old locale and switch to "C" because the locale
  78.  * influences the formatting of %f and we want it a certain way.
  79.  */
  80. saved_locale = setlocale(LC_ALL, 0);
  81. setlocale(LC_ALL, "C");
  82. #if defined _MSC_VER || defined __MINGW32__
  83. _snprintf(buffer, sizeof(buffer)-1, format, name, value);
  84. #else
  85. snprintf(buffer, sizeof(buffer)-1, format, name, value);
  86. #endif
  87. setlocale(LC_ALL, saved_locale);
  88. entry.entry = (FLAC__byte *)buffer;
  89. entry.length = strlen(buffer);
  90. return FLAC__metadata_object_vorbiscomment_append_comment(block, entry, /*copy=*/true);
  91. }
  92. FLAC__bool grabbag__replaygain_is_valid_sample_frequency(unsigned sample_frequency)
  93. {
  94. static const unsigned valid_sample_rates[] = {
  95. 8000,
  96. 11025,
  97. 12000,
  98. 16000,
  99. 22050,
  100. 24000,
  101. 32000,
  102. 44100,
  103. 48000
  104. };
  105. static const unsigned n_valid_sample_rates = sizeof(valid_sample_rates) / sizeof(valid_sample_rates[0]);
  106. unsigned i;
  107. for(i = 0; i < n_valid_sample_rates; i++)
  108. if(sample_frequency == valid_sample_rates[i])
  109. return true;
  110. return false;
  111. }
  112. FLAC__bool grabbag__replaygain_init(unsigned sample_frequency)
  113. {
  114. title_peak_ = album_peak_ = 0.0;
  115. return InitGainAnalysis((long)sample_frequency) == INIT_GAIN_ANALYSIS_OK;
  116. }
  117. FLAC__bool grabbag__replaygain_analyze(const FLAC__int32 * const input[], FLAC__bool is_stereo, unsigned bps, unsigned samples)
  118. {
  119. /* using a small buffer improves data locality; we'd like it to fit easily in the dcache */
  120. static Float_t lbuffer[2048], rbuffer[2048];
  121. static const unsigned nbuffer = sizeof(lbuffer) / sizeof(lbuffer[0]);
  122. FLAC__int32 block_peak = 0, s;
  123. unsigned i, j;
  124. FLAC__ASSERT(bps >= 4 && bps <= FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE);
  125. FLAC__ASSERT(FLAC__MIN_BITS_PER_SAMPLE == 4);
  126. /*
  127.  * We use abs() on a FLAC__int32 which is undefined for the most negative value.
  128.  * If the reference codec ever handles 32bps we will have to write a special
  129.  * case here.
  130.  */
  131. FLAC__ASSERT(FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE < 32);
  132. if(bps == 16) {
  133. if(is_stereo) {
  134. j = 0;
  135. while(samples > 0) {
  136. const unsigned n = local_min(samples, nbuffer);
  137. for(i = 0; i < n; i++, j++) {
  138. s = input[0][j];
  139. lbuffer[i] = (Float_t)s;
  140. s = abs(s);
  141. block_peak = local_max(block_peak, s);
  142. s = input[1][j];
  143. rbuffer[i] = (Float_t)s;
  144. s = abs(s);
  145. block_peak = local_max(block_peak, s);
  146. }
  147. samples -= n;
  148. if(AnalyzeSamples(lbuffer, rbuffer, n, 2) != GAIN_ANALYSIS_OK)
  149. return false;
  150. }
  151. }
  152. else {
  153. j = 0;
  154. while(samples > 0) {
  155. const unsigned n = local_min(samples, nbuffer);
  156. for(i = 0; i < n; i++, j++) {
  157. s = input[0][j];
  158. lbuffer[i] = (Float_t)s;
  159. s = abs(s);
  160. block_peak = local_max(block_peak, s);
  161. }
  162. samples -= n;
  163. if(AnalyzeSamples(lbuffer, 0, n, 1) != GAIN_ANALYSIS_OK)
  164. return false;
  165. }
  166. }
  167. }
  168. else { /* bps must be < 32 according to above assertion */
  169. const double scale = (
  170. (bps > 16)?
  171. (double)1. / (double)(1u << (bps - 16)) :
  172. (double)(1u << (16 - bps))
  173. );
  174. if(is_stereo) {
  175. j = 0;
  176. while(samples > 0) {
  177. const unsigned n = local_min(samples, nbuffer);
  178. for(i = 0; i < n; i++, j++) {
  179. s = input[0][j];
  180. lbuffer[i] = (Float_t)(scale * (double)s);
  181. s = abs(s);
  182. block_peak = local_max(block_peak, s);
  183. s = input[1][j];
  184. rbuffer[i] = (Float_t)(scale * (double)s);
  185. s = abs(s);
  186. block_peak = local_max(block_peak, s);
  187. }
  188. samples -= n;
  189. if(AnalyzeSamples(lbuffer, rbuffer, n, 2) != GAIN_ANALYSIS_OK)
  190. return false;
  191. }
  192. }
  193. else {
  194. j = 0;
  195. while(samples > 0) {
  196. const unsigned n = local_min(samples, nbuffer);
  197. for(i = 0; i < n; i++, j++) {
  198. s = input[0][j];
  199. lbuffer[i] = (Float_t)(scale * (double)s);
  200. s = abs(s);
  201. block_peak = local_max(block_peak, s);
  202. }
  203. samples -= n;
  204. if(AnalyzeSamples(lbuffer, 0, n, 1) != GAIN_ANALYSIS_OK)
  205. return false;
  206. }
  207. }
  208. }
  209. {
  210. const double peak_scale = (double)(1u << (bps - 1));
  211. double peak = (double)block_peak / peak_scale;
  212. if(peak > title_peak_)
  213. title_peak_ = peak;
  214. if(peak > album_peak_)
  215. album_peak_ = peak;
  216. }
  217. return true;
  218. }
  219. void grabbag__replaygain_get_album(float *gain, float *peak)
  220. {
  221. *gain = (float)GetAlbumGain();
  222. *peak = (float)album_peak_;
  223. album_peak_ = 0.0;
  224. }
  225. void grabbag__replaygain_get_title(float *gain, float *peak)
  226. {
  227. *gain = (float)GetTitleGain();
  228. *peak = (float)title_peak_;
  229. title_peak_ = 0.0;
  230. }
  231. typedef struct {
  232. unsigned channels;
  233. unsigned bits_per_sample;
  234. unsigned sample_rate;
  235. FLAC__bool error;
  236. } DecoderInstance;
  237. static FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__FileDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  238. {
  239. DecoderInstance *instance = (DecoderInstance*)client_data;
  240. const unsigned bits_per_sample = frame->header.bits_per_sample;
  241. const unsigned channels = frame->header.channels;
  242. const unsigned sample_rate = frame->header.sample_rate;
  243. const unsigned samples = frame->header.blocksize;
  244. (void)decoder;
  245. if(
  246. !instance->error &&
  247. (channels == 2 || channels == 1) &&
  248. bits_per_sample == instance->bits_per_sample &&
  249. channels == instance->channels &&
  250. sample_rate == instance->sample_rate
  251. ) {
  252. instance->error = !grabbag__replaygain_analyze(buffer, channels==2, bits_per_sample, samples);
  253. }
  254. else {
  255. instance->error = true;
  256. }
  257. if(!instance->error)
  258. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  259. else
  260. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  261. }
  262. static void metadata_callback_(const FLAC__FileDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  263. {
  264. DecoderInstance *instance = (DecoderInstance*)client_data;
  265. (void)decoder;
  266. if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
  267. instance->bits_per_sample = metadata->data.stream_info.bits_per_sample;
  268. instance->channels = metadata->data.stream_info.channels;
  269. instance->sample_rate = metadata->data.stream_info.sample_rate;
  270. if(instance->channels != 1 && instance->channels != 2) {
  271. instance->error = true;
  272. return;
  273. }
  274. if(!grabbag__replaygain_is_valid_sample_frequency(instance->sample_rate)) {
  275. instance->error = true;
  276. return;
  277. }
  278. }
  279. }
  280. static void error_callback_(const FLAC__FileDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  281. {
  282. DecoderInstance *instance = (DecoderInstance*)client_data;
  283. (void)decoder, (void)status;
  284. instance->error = true;
  285. }
  286. const char *grabbag__replaygain_analyze_file(const char *filename, float *title_gain, float *title_peak)
  287. {
  288. DecoderInstance instance;
  289. FLAC__FileDecoder *decoder = FLAC__file_decoder_new();
  290. if(0 == decoder)
  291. return "memory allocation error";
  292. instance.error = false;
  293. /* It does these three by default but lets be explicit: */
  294. FLAC__file_decoder_set_md5_checking(decoder, false);
  295. FLAC__file_decoder_set_metadata_ignore_all(decoder);
  296. FLAC__file_decoder_set_metadata_respond(decoder, FLAC__METADATA_TYPE_STREAMINFO);
  297. FLAC__file_decoder_set_filename(decoder, filename);
  298. FLAC__file_decoder_set_write_callback(decoder, write_callback_);
  299. FLAC__file_decoder_set_metadata_callback(decoder, metadata_callback_);
  300. FLAC__file_decoder_set_error_callback(decoder, error_callback_);
  301. FLAC__file_decoder_set_client_data(decoder, &instance);
  302. if(FLAC__file_decoder_init(decoder) != FLAC__FILE_DECODER_OK) {
  303. FLAC__file_decoder_delete(decoder);
  304. return "initializing decoder";
  305. }
  306. if(!FLAC__file_decoder_process_until_end_of_file(decoder) || instance.error) {
  307. FLAC__file_decoder_delete(decoder);
  308. return "decoding file";
  309. }
  310. FLAC__file_decoder_delete(decoder);
  311. grabbag__replaygain_get_title(title_gain, title_peak);
  312. return 0;
  313. }
  314. const char *grabbag__replaygain_store_to_vorbiscomment(FLAC__StreamMetadata *block, float album_gain, float album_peak, float title_gain, float title_peak)
  315. {
  316. const char *error;
  317. if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_title(block, title_gain, title_peak)))
  318. return error;
  319. if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_album(block, album_gain, album_peak)))
  320. return error;
  321. return 0;
  322. }
  323. const char *grabbag__replaygain_store_to_vorbiscomment_album(FLAC__StreamMetadata *block, float album_gain, float album_peak)
  324. {
  325. FLAC__ASSERT(0 != block);
  326. FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
  327. if(
  328. FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)tag_album_gain_) < 0 ||
  329. FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)tag_album_peak_) < 0
  330. )
  331. return "memory allocation error";
  332. if(
  333. !append_tag_(block, peak_format_, tag_album_peak_, album_peak) ||
  334. !append_tag_(block, gain_format_, tag_album_gain_, album_gain)
  335. )
  336. return "memory allocation error";
  337. return 0;
  338. }
  339. const char *grabbag__replaygain_store_to_vorbiscomment_title(FLAC__StreamMetadata *block, float title_gain, float title_peak)
  340. {
  341. FLAC__ASSERT(0 != block);
  342. FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
  343. if(
  344. FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)tag_title_gain_) < 0 ||
  345. FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)tag_title_peak_) < 0
  346. )
  347. return "memory allocation error";
  348. if(
  349. !append_tag_(block, peak_format_, tag_title_peak_, title_peak) ||
  350. !append_tag_(block, gain_format_, tag_title_gain_, title_gain)
  351. )
  352. return "memory allocation error";
  353. return 0;
  354. }
  355. static const char *store_to_file_pre_(const char *filename, FLAC__Metadata_Chain **chain, FLAC__StreamMetadata **block)
  356. {
  357. FLAC__Metadata_Iterator *iterator;
  358. const char *error;
  359. FLAC__bool found_vc_block = false;
  360. if(0 == (*chain = FLAC__metadata_chain_new()))
  361. return "memory allocation error";
  362. if(!FLAC__metadata_chain_read(*chain, filename)) {
  363. error = FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(*chain)];
  364. FLAC__metadata_chain_delete(*chain);
  365. return error;
  366. }
  367. if(0 == (iterator = FLAC__metadata_iterator_new())) {
  368. FLAC__metadata_chain_delete(*chain);
  369. return "memory allocation error";
  370. }
  371. FLAC__metadata_iterator_init(iterator, *chain);
  372. do {
  373. *block = FLAC__metadata_iterator_get_block(iterator);
  374. if((*block)->type == FLAC__METADATA_TYPE_VORBIS_COMMENT)
  375. found_vc_block = true;
  376. } while(!found_vc_block && FLAC__metadata_iterator_next(iterator));
  377. if(!found_vc_block) {
  378. /* create a new block */
  379. *block = FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT);
  380. if(0 == *block) {
  381. FLAC__metadata_chain_delete(*chain);
  382. FLAC__metadata_iterator_delete(iterator);
  383. return "memory allocation error";
  384. }
  385. while(FLAC__metadata_iterator_next(iterator))
  386. ;
  387. if(!FLAC__metadata_iterator_insert_block_after(iterator, *block)) {
  388. error = FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(*chain)];
  389. FLAC__metadata_chain_delete(*chain);
  390. FLAC__metadata_iterator_delete(iterator);
  391. return error;
  392. }
  393. /* iterator is left pointing to new block */
  394. FLAC__ASSERT(FLAC__metadata_iterator_get_block(iterator) == *block);
  395. }
  396. FLAC__metadata_iterator_delete(iterator);
  397. FLAC__ASSERT(0 != *block);
  398. FLAC__ASSERT((*block)->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
  399. return 0;
  400. }
  401. static const char *store_to_file_post_(const char *filename, FLAC__Metadata_Chain *chain, FLAC__bool preserve_modtime)
  402. {
  403. struct stat stats;
  404. const FLAC__bool have_stats = get_file_stats_(filename, &stats);
  405. (void)grabbag__file_change_stats(filename, /*read_only=*/false);
  406. FLAC__metadata_chain_sort_padding(chain);
  407. if(!FLAC__metadata_chain_write(chain, /*use_padding=*/true, preserve_modtime)) {
  408. FLAC__metadata_chain_delete(chain);
  409. return FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(chain)];
  410. }
  411. FLAC__metadata_chain_delete(chain);
  412. if(have_stats)
  413. set_file_stats_(filename, &stats);
  414. return 0;
  415. }
  416. const char *grabbag__replaygain_store_to_file(const char *filename, float album_gain, float album_peak, float title_gain, float title_peak, FLAC__bool preserve_modtime)
  417. {
  418. FLAC__Metadata_Chain *chain;
  419. FLAC__StreamMetadata *block;
  420. const char *error;
  421. if(0 != (error = store_to_file_pre_(filename, &chain, &block)))
  422. return error;
  423. if(0 != (error = grabbag__replaygain_store_to_vorbiscomment(block, album_gain, album_peak, title_gain, title_peak))) {
  424. FLAC__metadata_chain_delete(chain);
  425. return error;
  426. }
  427. if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime)))
  428. return error;
  429. return 0;
  430. }
  431. const char *grabbag__replaygain_store_to_file_album(const char *filename, float album_gain, float album_peak, FLAC__bool preserve_modtime)
  432. {
  433. FLAC__Metadata_Chain *chain;
  434. FLAC__StreamMetadata *block;
  435. const char *error;
  436. if(0 != (error = store_to_file_pre_(filename, &chain, &block)))
  437. return error;
  438. if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_album(block, album_gain, album_peak))) {
  439. FLAC__metadata_chain_delete(chain);
  440. return error;
  441. }
  442. if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime)))
  443. return error;
  444. return 0;
  445. }
  446. const char *grabbag__replaygain_store_to_file_title(const char *filename, float title_gain, float title_peak, FLAC__bool preserve_modtime)
  447. {
  448. FLAC__Metadata_Chain *chain;
  449. FLAC__StreamMetadata *block;
  450. const char *error;
  451. if(0 != (error = store_to_file_pre_(filename, &chain, &block)))
  452. return error;
  453. if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_title(block, title_gain, title_peak))) {
  454. FLAC__metadata_chain_delete(chain);
  455. return error;
  456. }
  457. if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime)))
  458. return error;
  459. return 0;
  460. }
  461. static FLAC__bool parse_double_(const FLAC__StreamMetadata_VorbisComment_Entry *entry, double *val)
  462. {
  463. char s[32], *end;
  464. const char *p, *q;
  465. double v;
  466. FLAC__ASSERT(0 != entry);
  467. FLAC__ASSERT(0 != val);
  468. p = (const char *)entry->entry;
  469. q = strchr(p, '=');
  470. if(0 == q)
  471. return false;
  472. q++;
  473. memset(s, 0, sizeof(s)-1);
  474. strncpy(s, q, local_min(sizeof(s)-1, entry->length - (q-p)));
  475. v = strtod(s, &end);
  476. if(end == s)
  477. return false;
  478. *val = v;
  479. return true;
  480. }
  481. FLAC__bool grabbag__replaygain_load_from_vorbiscomment(const FLAC__StreamMetadata *block, FLAC__bool album_mode, double *gain, double *peak)
  482. {
  483. int gain_offset, peak_offset;
  484. FLAC__ASSERT(0 != block);
  485. FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
  486. if(0 > (gain_offset = FLAC__metadata_object_vorbiscomment_find_entry_from(block, /*offset=*/0, (const char *)(album_mode? tag_album_gain_ : tag_title_gain_))))
  487. return false;
  488. if(0 > (peak_offset = FLAC__metadata_object_vorbiscomment_find_entry_from(block, /*offset=*/0, (const char *)(album_mode? tag_album_peak_ : tag_title_peak_))))
  489. return false;
  490. if(!parse_double_(block->data.vorbis_comment.comments + gain_offset, gain))
  491. return false;
  492. if(!parse_double_(block->data.vorbis_comment.comments + peak_offset, peak))
  493. return false;
  494. return true;
  495. }
  496. double grabbag__replaygain_compute_scale_factor(double peak, double gain, double preamp, FLAC__bool prevent_clipping)
  497. {
  498. double scale;
  499. FLAC__ASSERT(peak >= 0.0);
  500.   gain += preamp;
  501. scale = (float) pow(10.0, gain * 0.05);
  502. if(prevent_clipping && peak > 0.0) {
  503. const double max_scale = (float)(1.0 / peak);
  504. if(scale > max_scale)
  505. scale = max_scale;
  506. }
  507. return scale;
  508. }