initial import
[flac.git] / src / share / replaygain / replaygain.c
1 /* replaygain - Convenience lib for calculating/storing ReplayGain in FLAC
2  * Copyright (C) 2002  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
19 #include "share/file_utils.h"
20 #include "share/replaygain.h"
21 #include "share/gain_analysis.h"
22 #include "FLAC/assert.h"
23 #include "FLAC/file_decoder.h"
24 #include "FLAC/metadata.h"
25 #include <math.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #if defined _MSC_VER || defined __MINGW32__
30 #include <io.h> /* for chmod() */
31 #endif
32 #include <sys/stat.h> /* for stat(), maybe chmod() */
33
34 #ifdef local_min
35 #undef local_min
36 #endif
37 #define local_min(a,b) ((a)<(b)?(a):(b))
38
39 #ifdef local_max
40 #undef local_max
41 #endif
42 #define local_max(a,b) ((a)>(b)?(a):(b))
43
44 static const FLAC__byte *tag_title_gain_ = "REPLAYGAIN_TRACK_GAIN";
45 static const FLAC__byte *tag_title_peak_ = "REPLAYGAIN_TRACK_PEAK";
46 static const FLAC__byte *tag_album_gain_ = "REPLAYGAIN_ALBUM_GAIN";
47 static const FLAC__byte *tag_album_peak_ = "REPLAYGAIN_ALBUM_PEAK";
48 static const char *peak_format_ = "%s=%1.8f";
49 static const char *gain_format_ = "%s=%+2.2f dB";
50
51 static double album_peak_, title_peak_;
52
53 REPLAYGAIN_API const unsigned FLAC__REPLAYGAIN_MAX_TAG_SPACE_REQUIRED = 148;
54 /*
55         FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 21 + 1 + 10 +
56         FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 21 + 1 + 12 +
57         FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 21 + 1 + 10 +
58         FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 21 + 1 + 12
59 */
60
61
62 static FLAC__bool get_file_stats_(const char *filename, struct stat *stats)
63 {
64         FLAC__ASSERT(0 != filename);
65         FLAC__ASSERT(0 != stats);
66         return (0 == stat(filename, stats));
67 }
68
69 static void set_file_stats_(const char *filename, struct stat *stats)
70 {
71         FLAC__ASSERT(0 != filename);
72         FLAC__ASSERT(0 != stats);
73
74         (void)chmod(filename, stats->st_mode);
75 }
76
77 static FLAC__bool append_tag_(FLAC__StreamMetadata *block, const char *format, const FLAC__byte *name, float value)
78 {
79         char buffer[256];
80         FLAC__StreamMetadata_VorbisComment_Entry entry;
81
82         FLAC__ASSERT(0 != block);
83         FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
84         FLAC__ASSERT(0 != name);
85         FLAC__ASSERT(0 != value);
86
87         buffer[sizeof(buffer)-1] = '\0';
88         snprintf(buffer, sizeof(buffer)-1, format, name, value);
89
90         entry.entry = buffer;
91         entry.length = strlen(buffer);
92
93         return FLAC__metadata_object_vorbiscomment_insert_comment(block, block->data.vorbis_comment.num_comments, entry, /*copy=*/true);
94 }
95
96 REPLAYGAIN_API FLAC__bool FLAC__replaygain_is_valid_sample_frequency(unsigned sample_frequency)
97 {
98         static const unsigned valid_sample_rates[] = {
99                 8000,
100                 11025,
101                 12000,
102                 16000,
103                 22050,
104                 24000,
105                 32000,
106                 44100,
107                 48000
108         };
109         static const unsigned n_valid_sample_rates = sizeof(valid_sample_rates) / sizeof(valid_sample_rates[0]);
110
111         unsigned i;
112
113         for(i = 0; i < n_valid_sample_rates; i++)
114                 if(sample_frequency == valid_sample_rates[i])
115                         return true;
116         return false;
117 }
118
119 REPLAYGAIN_API FLAC__bool FLAC__replaygain_init(unsigned sample_frequency)
120 {
121         title_peak_ = album_peak_ = 0.0;
122         return InitGainAnalysis((long)sample_frequency) == INIT_GAIN_ANALYSIS_OK;
123 }
124
125 REPLAYGAIN_API FLAC__bool FLAC__replaygain_analyze(const FLAC__int32 * const input[], FLAC__bool is_stereo, unsigned bps, unsigned samples)
126 {
127         /* using a small buffer improves data locality; we'd like it to fit easily in the dcache */
128         static Float_t lbuffer[2048], rbuffer[2048];
129         static const unsigned nbuffer = sizeof(lbuffer) / sizeof(lbuffer[0]);
130         FLAC__int32 block_peak = 0, s;
131         unsigned i, j;
132
133         FLAC__ASSERT(bps >= 4 && bps <= FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE);
134         FLAC__ASSERT(FLAC__MIN_BITS_PER_SAMPLE == 4);
135         /*
136          * We use abs() on a FLAC__int32 which is undefined for the most negative value.
137          * If the reference codec ever handles 32bps we will have to write a special
138          * case here.
139          */
140         FLAC__ASSERT(FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE < 32);
141
142         if(bps == 16) {
143                 if(is_stereo) {
144                         j = 0;
145                         while(samples > 0) {
146                                 const unsigned n = local_min(samples, nbuffer);
147                                 for(i = 0; i < n; i++, j++) {
148                                         s = input[0][j];
149                                         lbuffer[i] = (Float_t)s;
150                                         s = abs(s);
151                                         block_peak = local_max(block_peak, s);
152
153                                         s = input[1][j];
154                                         rbuffer[i] = (Float_t)s;
155                                         s = abs(s);
156                                         block_peak = local_max(block_peak, s);
157                                 }
158                                 samples -= n;
159                                 if(AnalyzeSamples(lbuffer, rbuffer, n, 2) != GAIN_ANALYSIS_OK)
160                                         return false;
161                         }
162                 }
163                 else {
164                         j = 0;
165                         while(samples > 0) {
166                                 const unsigned n = local_min(samples, nbuffer);
167                                 for(i = 0; i < n; i++, j++) {
168                                         s = input[0][j];
169                                         lbuffer[i] = (Float_t)s;
170                                         s = abs(s);
171                                         block_peak = local_max(block_peak, s);
172                                 }
173                                 samples -= n;
174                                 if(AnalyzeSamples(lbuffer, 0, n, 1) != GAIN_ANALYSIS_OK)
175                                         return false;
176                         }
177                 }
178         }
179         else { /* bps must be < 32 according to above assertion */
180                 const double scale = (
181                         (bps > 16)?
182                                 (double)1. / (double)(1u << (bps - 16)) :
183                                 (double)(1u << (16 - bps))
184                 );
185
186                 if(is_stereo) {
187                         j = 0;
188                         while(samples > 0) {
189                                 const unsigned n = local_min(samples, nbuffer);
190                                 for(i = 0; i < n; i++, j++) {
191                                         s = input[0][j];
192                                         lbuffer[i] = (Float_t)(scale * (double)s);
193                                         s = abs(s);
194                                         block_peak = local_max(block_peak, s);
195
196                                         s = input[1][j];
197                                         rbuffer[i] = (Float_t)(scale * (double)s);
198                                         s = abs(s);
199                                         block_peak = local_max(block_peak, s);
200                                 }
201                                 samples -= n;
202                                 if(AnalyzeSamples(lbuffer, rbuffer, n, 2) != GAIN_ANALYSIS_OK)
203                                         return false;
204                         }
205                 }
206                 else {
207                         j = 0;
208                         while(samples > 0) {
209                                 const unsigned n = local_min(samples, nbuffer);
210                                 for(i = 0; i < n; i++, j++) {
211                                         s = input[0][j];
212                                         lbuffer[i] = (Float_t)(scale * (double)s);
213                                         s = abs(s);
214                                         block_peak = local_max(block_peak, s);
215                                 }
216                                 samples -= n;
217                                 if(AnalyzeSamples(lbuffer, 0, n, 1) != GAIN_ANALYSIS_OK)
218                                         return false;
219                         }
220                 }
221         }
222
223         {
224                 const double peak_scale = (double)(1u << (bps - 1));
225                 double peak = (double)block_peak / peak_scale;
226                 if(peak > title_peak_)
227                         title_peak_ = peak;
228                 if(peak > album_peak_)
229                         album_peak_ = peak;
230         }
231
232         return true;
233 }
234
235 REPLAYGAIN_API void FLAC__replaygain_get_album(float *gain, float *peak)
236 {
237         *gain = (float)GetAlbumGain();
238         *peak = (float)album_peak_;
239         album_peak_ = 0.0;
240 }
241
242 REPLAYGAIN_API void FLAC__replaygain_get_title(float *gain, float *peak)
243 {
244         *gain = (float)GetTitleGain();
245         *peak = (float)title_peak_;
246         title_peak_ = 0.0;
247 }
248
249
250 typedef struct {
251         unsigned channels;
252         unsigned bits_per_sample;
253         unsigned sample_rate;
254         FLAC__bool error;
255 } DecoderInstance;
256
257 static FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__FileDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
258 {
259         DecoderInstance *instance = (DecoderInstance*)client_data;
260         const unsigned bits_per_sample = frame->header.bits_per_sample;
261         const unsigned channels = frame->header.channels;
262         const unsigned sample_rate = frame->header.sample_rate;
263         const unsigned samples = frame->header.blocksize;
264
265         (void)decoder;
266
267         if(
268                 !instance->error &&
269                 (channels == 2 || channels == 1) &&
270                 bits_per_sample == instance->bits_per_sample &&
271                 channels == instance->channels &&
272                 sample_rate == instance->sample_rate
273         ) {
274                 instance->error = !FLAC__replaygain_analyze(buffer, channels==2, bits_per_sample, samples);
275         }
276         else {
277                 instance->error = true;
278         }
279
280         if(!instance->error)
281                 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
282         else
283                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
284 }
285
286 static void metadata_callback_(const FLAC__FileDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
287 {
288         DecoderInstance *instance = (DecoderInstance*)client_data;
289
290         (void)decoder;
291
292         if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
293                 instance->bits_per_sample = metadata->data.stream_info.bits_per_sample;
294                 instance->channels = metadata->data.stream_info.channels;
295                 instance->sample_rate = metadata->data.stream_info.sample_rate;
296
297                 if(instance->channels != 1 && instance->channels != 2) {
298                         instance->error = true;
299                         return;
300                 }
301
302                 if(!FLAC__replaygain_is_valid_sample_frequency(instance->sample_rate)) {
303                         instance->error = true;
304                         return;
305                 }
306         }
307 }
308
309 static void error_callback_(const FLAC__FileDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
310 {
311         DecoderInstance *instance = (DecoderInstance*)client_data;
312
313         (void)decoder, (void)status;
314
315         instance->error = true;
316 }
317
318 REPLAYGAIN_API const char *FLAC__replaygain_analyze_file(const char *filename, float *title_gain, float *title_peak)
319 {
320         DecoderInstance instance;
321         FLAC__FileDecoder *decoder = FLAC__file_decoder_new();
322
323         if(0 == decoder)
324                 return "memory allocation error";
325
326         instance.error = false;
327
328         /* It does these three by default but lets be explicit: */
329         FLAC__file_decoder_set_md5_checking(decoder, false);
330         FLAC__file_decoder_set_metadata_ignore_all(decoder);
331         FLAC__file_decoder_set_metadata_respond(decoder, FLAC__METADATA_TYPE_STREAMINFO);
332
333         FLAC__file_decoder_set_filename(decoder, filename);
334         FLAC__file_decoder_set_write_callback(decoder, write_callback_);
335         FLAC__file_decoder_set_metadata_callback(decoder, metadata_callback_);
336         FLAC__file_decoder_set_error_callback(decoder, error_callback_);
337         FLAC__file_decoder_set_client_data(decoder, &instance);
338
339         if(FLAC__file_decoder_init(decoder) != FLAC__FILE_DECODER_OK) {
340                 FLAC__file_decoder_delete(decoder);
341                 return "initializing decoder";
342         }
343
344         if(!FLAC__file_decoder_process_until_end_of_file(decoder) || instance.error) {
345                 FLAC__file_decoder_delete(decoder);
346                 return "decoding file";
347         }
348
349         FLAC__file_decoder_delete(decoder);
350
351         FLAC__replaygain_get_title(title_gain, title_peak);
352
353         return 0;
354 }
355
356 REPLAYGAIN_API const char *FLAC__replaygain_store_to_vorbiscomment(FLAC__StreamMetadata *block, float album_gain, float album_peak, float title_gain, float title_peak)
357 {
358         const char *error;
359
360         if(0 != (error = FLAC__replaygain_store_to_vorbiscomment_title(block, title_gain, title_peak)))
361                 return error;
362
363         if(0 != (error = FLAC__replaygain_store_to_vorbiscomment_album(block, album_gain, album_peak)))
364                 return error;
365
366         return 0;
367 }
368
369 REPLAYGAIN_API const char *FLAC__replaygain_store_to_vorbiscomment_album(FLAC__StreamMetadata *block, float album_gain, float album_peak)
370 {
371         FLAC__ASSERT(0 != block);
372         FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
373
374         if(
375                 FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, tag_album_gain_) < 0 ||
376                 FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, tag_album_peak_) < 0
377         )
378                 return "memory allocation error";
379
380         if(
381                 !append_tag_(block, peak_format_, tag_album_peak_, album_peak) ||
382                 !append_tag_(block, gain_format_, tag_album_gain_, album_gain)
383         )
384                 return "memory allocation error";
385
386         return 0;
387 }
388
389 REPLAYGAIN_API const char *FLAC__replaygain_store_to_vorbiscomment_title(FLAC__StreamMetadata *block, float title_gain, float title_peak)
390 {
391         FLAC__ASSERT(0 != block);
392         FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
393
394         if(
395                 FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, tag_title_gain_) < 0 ||
396                 FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, tag_title_peak_) < 0
397         )
398                 return "memory allocation error";
399
400         if(
401                 !append_tag_(block, peak_format_, tag_title_peak_, title_peak) ||
402                 !append_tag_(block, gain_format_, tag_title_gain_, title_gain)
403         )
404                 return "memory allocation error";
405
406         return 0;
407 }
408
409 static const char *store_to_file_pre_(const char *filename, FLAC__Metadata_Chain **chain, FLAC__StreamMetadata **block)
410 {
411         FLAC__Metadata_Iterator *iterator;
412         const char *error;
413         FLAC__bool found_vc_block = false;
414
415         if(0 == (*chain = FLAC__metadata_chain_new()))
416                 return "memory allocation error";
417
418         if(!FLAC__metadata_chain_read(*chain, filename)) {
419                 error = FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(*chain)];
420                 FLAC__metadata_chain_delete(*chain);
421                 return error;
422         }
423
424         if(0 == (iterator = FLAC__metadata_iterator_new())) {
425                 FLAC__metadata_chain_delete(*chain);
426                 return "memory allocation error";
427         }
428
429         FLAC__metadata_iterator_init(iterator, *chain);
430
431         do {
432                 *block = FLAC__metadata_iterator_get_block(iterator);
433                 if((*block)->type == FLAC__METADATA_TYPE_VORBIS_COMMENT)
434                         found_vc_block = true;
435         } while(!found_vc_block && FLAC__metadata_iterator_next(iterator));
436
437         if(!found_vc_block) {
438                 /* create a new block */
439                 *block = FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT);
440                 if(0 == *block) {
441                         FLAC__metadata_chain_delete(*chain);
442                         FLAC__metadata_iterator_delete(iterator);
443                         return "memory allocation error";
444                 }
445                 while(FLAC__metadata_iterator_next(iterator))
446                         ;
447                 if(!FLAC__metadata_iterator_insert_block_after(iterator, *block)) {
448                         error = FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(*chain)];
449                         FLAC__metadata_chain_delete(*chain);
450                         FLAC__metadata_iterator_delete(iterator);
451                         return error;
452                 }
453                 /* iterator is left pointing to new block */
454                 FLAC__ASSERT(FLAC__metadata_iterator_get_block(iterator) == *block);
455         }
456
457         FLAC__metadata_iterator_delete(iterator);
458
459         FLAC__ASSERT(0 != *block);
460         FLAC__ASSERT((*block)->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
461
462         return 0;
463 }
464
465 static const char *store_to_file_post_(const char *filename, FLAC__Metadata_Chain *chain, FLAC__bool preserve_modtime)
466 {
467         struct stat stats;
468         const FLAC__bool have_stats = get_file_stats_(filename, &stats);
469
470         (void)FLAC__file_utils_change_stats(filename, /*read_only=*/false);
471
472         FLAC__metadata_chain_sort_padding(chain);
473         if(!FLAC__metadata_chain_write(chain, /*use_padding=*/true, preserve_modtime)) {
474                 FLAC__metadata_chain_delete(chain);
475                 return FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(chain)];
476         }
477
478         FLAC__metadata_chain_delete(chain);
479
480         if(have_stats)
481                 set_file_stats_(filename, &stats);
482
483         return 0;
484 }
485
486 REPLAYGAIN_API const char *FLAC__replaygain_store_to_file(const char *filename, float album_gain, float album_peak, float title_gain, float title_peak, FLAC__bool preserve_modtime)
487 {
488         FLAC__Metadata_Chain *chain;
489         FLAC__StreamMetadata *block;
490         const char *error;
491
492         if(0 != (error = store_to_file_pre_(filename, &chain, &block)))
493                 return error;
494
495         if(0 != (error = FLAC__replaygain_store_to_vorbiscomment(block, album_gain, album_peak, title_gain, title_peak))) {
496                 FLAC__metadata_chain_delete(chain);
497                 return error;
498         }
499
500         if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime)))
501                 return error;
502
503         return 0;
504 }
505
506 REPLAYGAIN_API const char *FLAC__replaygain_store_to_file_album(const char *filename, float album_gain, float album_peak, FLAC__bool preserve_modtime)
507 {
508         FLAC__Metadata_Chain *chain;
509         FLAC__StreamMetadata *block;
510         const char *error;
511
512         if(0 != (error = store_to_file_pre_(filename, &chain, &block)))
513                 return error;
514
515         if(0 != (error = FLAC__replaygain_store_to_vorbiscomment_album(block, album_gain, album_peak))) {
516                 FLAC__metadata_chain_delete(chain);
517                 return error;
518         }
519
520         if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime)))
521                 return error;
522
523         return 0;
524 }
525
526 REPLAYGAIN_API const char *FLAC__replaygain_store_to_file_title(const char *filename, float title_gain, float title_peak, FLAC__bool preserve_modtime)
527 {
528         FLAC__Metadata_Chain *chain;
529         FLAC__StreamMetadata *block;
530         const char *error;
531
532         if(0 != (error = store_to_file_pre_(filename, &chain, &block)))
533                 return error;
534
535         if(0 != (error = FLAC__replaygain_store_to_vorbiscomment_title(block, title_gain, title_peak))) {
536                 FLAC__metadata_chain_delete(chain);
537                 return error;
538         }
539
540         if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime)))
541                 return error;
542
543         return 0;
544 }
545
546 static FLAC__bool parse_double_(const FLAC__StreamMetadata_VorbisComment_Entry *entry, double *val)
547 {
548         char s[32], *end;
549         const char *p, *q;
550         double v;
551
552         FLAC__ASSERT(0 != entry);
553         FLAC__ASSERT(0 != val);
554
555 fprintf(stderr,"@@@@ tag=[");fwrite(entry->entry,1,entry->length,stderr);fprintf(stderr,"]\n");
556         p = (const char *)entry->entry;
557         q = strchr(p, '=');
558         if(0 == q)
559                 return false;
560         q++;
561         memset(s, 0, sizeof(s)-1);
562         strncpy(s, q, local_min(sizeof(s)-1, entry->length - (q-p)));
563 fprintf(stderr,"@@@@ s=[%s]\n",s);
564
565         v = strtod(s, &end);
566         if(end == s)
567                 return false;
568
569         *val = v;
570 fprintf(stderr,"@@@@ v=[%0.12f]\n",v);
571         return true;
572 }
573
574 REPLAYGAIN_API FLAC__bool FLAC__replaygain_load_from_vorbiscomment(const FLAC__StreamMetadata *block, FLAC__bool album_mode, double *gain, double *peak)
575 {
576         int gain_offset, peak_offset;
577
578         FLAC__ASSERT(0 != block);
579         FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
580
581         if(0 > (gain_offset = FLAC__metadata_object_vorbiscomment_find_entry_from(block, /*offset=*/0, album_mode? tag_album_gain_ : tag_title_gain_)))
582                 return false;
583         if(0 > (peak_offset = FLAC__metadata_object_vorbiscomment_find_entry_from(block, /*offset=*/0, album_mode? tag_album_peak_ : tag_title_peak_)))
584                 return false;
585
586         if(!parse_double_(block->data.vorbis_comment.comments + gain_offset, gain))
587                 return false;
588         if(!parse_double_(block->data.vorbis_comment.comments + peak_offset, peak))
589                 return false;
590
591         return true;
592 }
593
594 REPLAYGAIN_API double FLAC__replaygain_compute_scale_factor(double peak, double gain, double preamp, FLAC__bool prevent_clipping)
595 {
596         double scale;
597         FLAC__ASSERT(peak >= 0.0);
598         gain += preamp;
599         scale = (float) pow(10.0, gain * 0.05);
600         if(prevent_clipping && peak > 0.0) {
601                 const double max_scale = (float)(1.0 / peak);
602                 if(scale > max_scale)
603                         scale = max_scale;
604         }
605         return scale;
606 }