]> 4ch.mooo.com Git - 16.git/blob - src/lib/dl/ext/flac/replaygain.c
looking at tesuto now~
[16.git] / src / lib / dl / ext / flac / replaygain.c
1 /* grabbag - Convenience lib for various routines common to several tools
2  * Copyright (C) 2002,2003,2004,2005,2006,2007  Josh Coalson
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library 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 GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
17  */
18
19 #if HAVE_CONFIG_H
20 #  include "config.h"
21 #endif
22
23 #include "share/grabbag.h"
24 #include "share/replaygain_analysis.h"
25 #include "flac/assert.h"
26 #include "flac/metadata.h"
27 #include "flac/stream_decoder.h"
28 #include <locale.h>
29 #include <math.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #if defined _MSC_VER || defined __MINGW32__
34 #include <io.h> /* for chmod() */
35 #endif
36 #include <sys/stat.h> /* for stat(), maybe chmod() */
37
38 #ifdef local_min
39 #undef local_min
40 #endif
41 #define local_min(a,b) ((a)<(b)?(a):(b))
42
43 #ifdef local_max
44 #undef local_max
45 #endif
46 #define local_max(a,b) ((a)>(b)?(a):(b))
47
48 static const char *reference_format_ = "%s=%2.1f dB";
49 static const char *gain_format_ = "%s=%+2.2f dB";
50 static const char *peak_format_ = "%s=%1.8f";
51
52 static double album_peak_, title_peak_;
53
54 const unsigned GRABBAG__REPLAYGAIN_MAX_TAG_SPACE_REQUIRED = 190;
55 /*
56         FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 29 + 1 + 8 +
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         FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 21 + 1 + 10 +
60         FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN/8 + 21 + 1 + 12
61 */
62
63 const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_REFERENCE_LOUDNESS = (const FLAC__byte * const)"REPLAYGAIN_REFERENCE_LOUDNESS";
64 const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_TITLE_GAIN = (const FLAC__byte * const)"REPLAYGAIN_TRACK_GAIN";
65 const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_TITLE_PEAK = (const FLAC__byte * const)"REPLAYGAIN_TRACK_PEAK";
66 const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_ALBUM_GAIN = (const FLAC__byte * const)"REPLAYGAIN_ALBUM_GAIN";
67 const FLAC__byte * const GRABBAG__REPLAYGAIN_TAG_ALBUM_PEAK = (const FLAC__byte * const)"REPLAYGAIN_ALBUM_PEAK";
68
69
70 static FLAC__bool get_file_stats_(const char *filename, struct stat *stats)
71 {
72         FLAC__ASSERT(0 != filename);
73         FLAC__ASSERT(0 != stats);
74         return (0 == stat(filename, stats));
75 }
76
77 static void set_file_stats_(const char *filename, struct stat *stats)
78 {
79         FLAC__ASSERT(0 != filename);
80         FLAC__ASSERT(0 != stats);
81 }
82
83 static FLAC__bool append_tag_(FLAC__StreamMetadata *block, const char *format, const FLAC__byte *name, float value)
84 {
85         char buffer[256];
86         char *saved_locale;
87         FLAC__StreamMetadata_VorbisComment_Entry entry;
88
89         FLAC__ASSERT(0 != block);
90         FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
91         FLAC__ASSERT(0 != format);
92         FLAC__ASSERT(0 != name);
93
94         buffer[sizeof(buffer)-1] = '\0';
95         /*
96          * We need to save the old locale and switch to "C" because the locale
97          * influences the formatting of %f and we want it a certain way.
98          */
99         saved_locale = strdup(setlocale(LC_ALL, 0));
100         if (0 == saved_locale)
101                 return false;
102         setlocale(LC_ALL, "C");
103 #if defined _MSC_VER || defined __MINGW32__
104         _snprintf(buffer, sizeof(buffer)-1, format, name, value);
105 #else
106         snprintf(buffer, sizeof(buffer)-1, format, name, value);
107 #endif
108         setlocale(LC_ALL, saved_locale);
109         free(saved_locale);
110
111         entry.entry = (FLAC__byte *)buffer;
112         entry.length = strlen(buffer);
113
114         return FLAC__metadata_object_vorbiscomment_append_comment(block, entry, /*copy=*/true);
115 }
116
117 FLAC__bool grabbag__replaygain_is_valid_sample_frequency(unsigned sample_frequency)
118 {
119         static const unsigned valid_sample_rates[] = {
120                 8000,
121                 11025,
122                 12000,
123                 16000,
124                 22050,
125                 24000,
126                 32000,
127                 44100,
128                 48000
129         };
130         static const unsigned n_valid_sample_rates = sizeof(valid_sample_rates) / sizeof(valid_sample_rates[0]);
131
132         unsigned i;
133
134         for(i = 0; i < n_valid_sample_rates; i++)
135                 if(sample_frequency == valid_sample_rates[i])
136                         return true;
137         return false;
138 }
139
140 FLAC__bool grabbag__replaygain_init(unsigned sample_frequency)
141 {
142         title_peak_ = album_peak_ = 0.0;
143         return InitGainAnalysis((long)sample_frequency) == INIT_GAIN_ANALYSIS_OK;
144 }
145
146 FLAC__bool grabbag__replaygain_analyze(const FLAC__int32 * const input[], FLAC__bool is_stereo, unsigned bps, unsigned samples)
147 {
148         /* using a small buffer improves data locality; we'd like it to fit easily in the dcache */
149         static Float_t lbuffer[2048], rbuffer[2048];
150         static const unsigned nbuffer = sizeof(lbuffer) / sizeof(lbuffer[0]);
151         FLAC__int32 block_peak = 0, s;
152         unsigned i, j;
153
154         FLAC__ASSERT(bps >= 4 && bps <= FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE);
155         FLAC__ASSERT(FLAC__MIN_BITS_PER_SAMPLE == 4);
156         /*
157          * We use abs() on a FLAC__int32 which is undefined for the most negative value.
158          * If the reference codec ever handles 32bps we will have to write a special
159          * case here.
160          */
161         FLAC__ASSERT(FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE < 32);
162
163         if(bps == 16) {
164                 if(is_stereo) {
165                         j = 0;
166                         while(samples > 0) {
167                                 const unsigned n = local_min(samples, nbuffer);
168                                 for(i = 0; i < n; i++, j++) {
169                                         s = input[0][j];
170                                         lbuffer[i] = (Float_t)s;
171                                         s = abs(s);
172                                         block_peak = local_max(block_peak, s);
173
174                                         s = input[1][j];
175                                         rbuffer[i] = (Float_t)s;
176                                         s = abs(s);
177                                         block_peak = local_max(block_peak, s);
178                                 }
179                                 samples -= n;
180                                 if(AnalyzeSamples(lbuffer, rbuffer, n, 2) != GAIN_ANALYSIS_OK)
181                                         return false;
182                         }
183                 }
184                 else {
185                         j = 0;
186                         while(samples > 0) {
187                                 const unsigned n = local_min(samples, nbuffer);
188                                 for(i = 0; i < n; i++, j++) {
189                                         s = input[0][j];
190                                         lbuffer[i] = (Float_t)s;
191                                         s = abs(s);
192                                         block_peak = local_max(block_peak, s);
193                                 }
194                                 samples -= n;
195                                 if(AnalyzeSamples(lbuffer, 0, n, 1) != GAIN_ANALYSIS_OK)
196                                         return false;
197                         }
198                 }
199         }
200         else { /* bps must be < 32 according to above assertion */
201                 const double scale = (
202                         (bps > 16)?
203                                 (double)1. / (double)(1u << (bps - 16)) :
204                                 (double)(1u << (16 - bps))
205                 );
206
207                 if(is_stereo) {
208                         j = 0;
209                         while(samples > 0) {
210                                 const unsigned n = local_min(samples, nbuffer);
211                                 for(i = 0; i < n; i++, j++) {
212                                         s = input[0][j];
213                                         lbuffer[i] = (Float_t)(scale * (double)s);
214                                         s = abs(s);
215                                         block_peak = local_max(block_peak, s);
216
217                                         s = input[1][j];
218                                         rbuffer[i] = (Float_t)(scale * (double)s);
219                                         s = abs(s);
220                                         block_peak = local_max(block_peak, s);
221                                 }
222                                 samples -= n;
223                                 if(AnalyzeSamples(lbuffer, rbuffer, n, 2) != GAIN_ANALYSIS_OK)
224                                         return false;
225                         }
226                 }
227                 else {
228                         j = 0;
229                         while(samples > 0) {
230                                 const unsigned n = local_min(samples, nbuffer);
231                                 for(i = 0; i < n; i++, j++) {
232                                         s = input[0][j];
233                                         lbuffer[i] = (Float_t)(scale * (double)s);
234                                         s = abs(s);
235                                         block_peak = local_max(block_peak, s);
236                                 }
237                                 samples -= n;
238                                 if(AnalyzeSamples(lbuffer, 0, n, 1) != GAIN_ANALYSIS_OK)
239                                         return false;
240                         }
241                 }
242         }
243
244         {
245                 const double peak_scale = (double)(1u << (bps - 1));
246                 double peak = (double)block_peak / peak_scale;
247                 if(peak > title_peak_)
248                         title_peak_ = peak;
249                 if(peak > album_peak_)
250                         album_peak_ = peak;
251         }
252
253         return true;
254 }
255
256 void grabbag__replaygain_get_album(float *gain, float *peak)
257 {
258         *gain = (float)GetAlbumGain();
259         *peak = (float)album_peak_;
260         album_peak_ = 0.0;
261 }
262
263 void grabbag__replaygain_get_title(float *gain, float *peak)
264 {
265         *gain = (float)GetTitleGain();
266         *peak = (float)title_peak_;
267         title_peak_ = 0.0;
268 }
269
270
271 typedef struct {
272         unsigned channels;
273         unsigned bits_per_sample;
274         unsigned sample_rate;
275         FLAC__bool error;
276 } DecoderInstance;
277
278 static FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
279 {
280         DecoderInstance *instance = (DecoderInstance*)client_data;
281         const unsigned bits_per_sample = frame->header.bits_per_sample;
282         const unsigned channels = frame->header.channels;
283         const unsigned sample_rate = frame->header.sample_rate;
284         const unsigned samples = frame->header.blocksize;
285
286         (void)decoder;
287
288         if(
289                 !instance->error &&
290                 (channels == 2 || channels == 1) &&
291                 bits_per_sample == instance->bits_per_sample &&
292                 channels == instance->channels &&
293                 sample_rate == instance->sample_rate
294         ) {
295                 instance->error = !grabbag__replaygain_analyze(buffer, channels==2, bits_per_sample, samples);
296         }
297         else {
298                 instance->error = true;
299         }
300
301         if(!instance->error)
302                 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
303         else
304                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
305 }
306
307 static void metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
308 {
309         DecoderInstance *instance = (DecoderInstance*)client_data;
310
311         (void)decoder;
312
313         if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
314                 instance->bits_per_sample = metadata->data.stream_info.bits_per_sample;
315                 instance->channels = metadata->data.stream_info.channels;
316                 instance->sample_rate = metadata->data.stream_info.sample_rate;
317
318                 if(instance->channels != 1 && instance->channels != 2) {
319                         instance->error = true;
320                         return;
321                 }
322
323                 if(!grabbag__replaygain_is_valid_sample_frequency(instance->sample_rate)) {
324                         instance->error = true;
325                         return;
326                 }
327         }
328 }
329
330 static void error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
331 {
332         DecoderInstance *instance = (DecoderInstance*)client_data;
333
334         (void)decoder, (void)status;
335
336         instance->error = true;
337 }
338
339 const char *grabbag__replaygain_analyze_file(const char *filename, float *title_gain, float *title_peak)
340 {
341         DecoderInstance instance;
342         FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
343
344         if(0 == decoder)
345                 return "memory allocation error";
346
347         instance.error = false;
348
349         /* It does these three by default but lets be explicit: */
350         FLAC__stream_decoder_set_md5_checking(decoder, false);
351         FLAC__stream_decoder_set_metadata_ignore_all(decoder);
352         FLAC__stream_decoder_set_metadata_respond(decoder, FLAC__METADATA_TYPE_STREAMINFO);
353
354         if(FLAC__stream_decoder_init_file(decoder, filename, write_callback_, metadata_callback_, error_callback_, &instance) != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
355                 FLAC__stream_decoder_delete(decoder);
356                 return "initializing decoder";
357         }
358
359         if(!FLAC__stream_decoder_process_until_end_of_stream(decoder) || instance.error) {
360                 FLAC__stream_decoder_delete(decoder);
361                 return "decoding file";
362         }
363
364         FLAC__stream_decoder_delete(decoder);
365
366         grabbag__replaygain_get_title(title_gain, title_peak);
367
368         return 0;
369 }
370
371 const char *grabbag__replaygain_store_to_vorbiscomment(FLAC__StreamMetadata *block, float album_gain, float album_peak, float title_gain, float title_peak)
372 {
373         const char *error;
374
375         if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_reference(block)))
376                 return error;
377
378         if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_title(block, title_gain, title_peak)))
379                 return error;
380
381         if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_album(block, album_gain, album_peak)))
382                 return error;
383
384         return 0;
385 }
386
387 const char *grabbag__replaygain_store_to_vorbiscomment_reference(FLAC__StreamMetadata *block)
388 {
389         FLAC__ASSERT(0 != block);
390         FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
391
392         if(FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)GRABBAG__REPLAYGAIN_TAG_REFERENCE_LOUDNESS) < 0)
393                 return "memory allocation error";
394
395         if(!append_tag_(block, reference_format_, GRABBAG__REPLAYGAIN_TAG_REFERENCE_LOUDNESS, ReplayGainReferenceLoudness))
396                 return "memory allocation error";
397
398         return 0;
399 }
400
401 const char *grabbag__replaygain_store_to_vorbiscomment_album(FLAC__StreamMetadata *block, float album_gain, float album_peak)
402 {
403         FLAC__ASSERT(0 != block);
404         FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
405
406         if(
407                 FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)GRABBAG__REPLAYGAIN_TAG_ALBUM_GAIN) < 0 ||
408                 FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)GRABBAG__REPLAYGAIN_TAG_ALBUM_PEAK) < 0
409         )
410                 return "memory allocation error";
411
412         if(
413                 !append_tag_(block, gain_format_, GRABBAG__REPLAYGAIN_TAG_ALBUM_GAIN, album_gain) ||
414                 !append_tag_(block, peak_format_, GRABBAG__REPLAYGAIN_TAG_ALBUM_PEAK, album_peak)
415         )
416                 return "memory allocation error";
417
418         return 0;
419 }
420
421 const char *grabbag__replaygain_store_to_vorbiscomment_title(FLAC__StreamMetadata *block, float title_gain, float title_peak)
422 {
423         FLAC__ASSERT(0 != block);
424         FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
425
426         if(
427                 FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)GRABBAG__REPLAYGAIN_TAG_TITLE_GAIN) < 0 ||
428                 FLAC__metadata_object_vorbiscomment_remove_entries_matching(block, (const char *)GRABBAG__REPLAYGAIN_TAG_TITLE_PEAK) < 0
429         )
430                 return "memory allocation error";
431
432         if(
433                 !append_tag_(block, gain_format_, GRABBAG__REPLAYGAIN_TAG_TITLE_GAIN, title_gain) ||
434                 !append_tag_(block, peak_format_, GRABBAG__REPLAYGAIN_TAG_TITLE_PEAK, title_peak)
435         )
436                 return "memory allocation error";
437
438         return 0;
439 }
440
441 static const char *store_to_file_pre_(const char *filename, FLAC__Metadata_Chain **chain, FLAC__StreamMetadata **block)
442 {
443         FLAC__Metadata_Iterator *iterator;
444         const char *error;
445         FLAC__bool found_vc_block = false;
446
447         if(0 == (*chain = FLAC__metadata_chain_new()))
448                 return "memory allocation error";
449
450         if(!FLAC__metadata_chain_read(*chain, filename)) {
451                 error = FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(*chain)];
452                 FLAC__metadata_chain_delete(*chain);
453                 return error;
454         }
455
456         if(0 == (iterator = FLAC__metadata_iterator_new())) {
457                 FLAC__metadata_chain_delete(*chain);
458                 return "memory allocation error";
459         }
460
461         FLAC__metadata_iterator_init(iterator, *chain);
462
463         do {
464                 *block = FLAC__metadata_iterator_get_block(iterator);
465                 if((*block)->type == FLAC__METADATA_TYPE_VORBIS_COMMENT)
466                         found_vc_block = true;
467         } while(!found_vc_block && FLAC__metadata_iterator_next(iterator));
468
469         if(!found_vc_block) {
470                 /* create a new block */
471                 *block = FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT);
472                 if(0 == *block) {
473                         FLAC__metadata_chain_delete(*chain);
474                         FLAC__metadata_iterator_delete(iterator);
475                         return "memory allocation error";
476                 }
477                 while(FLAC__metadata_iterator_next(iterator))
478                         ;
479                 if(!FLAC__metadata_iterator_insert_block_after(iterator, *block)) {
480                         error = FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(*chain)];
481                         FLAC__metadata_chain_delete(*chain);
482                         FLAC__metadata_iterator_delete(iterator);
483                         return error;
484                 }
485                 /* iterator is left pointing to new block */
486                 FLAC__ASSERT(FLAC__metadata_iterator_get_block(iterator) == *block);
487         }
488
489         FLAC__metadata_iterator_delete(iterator);
490
491         FLAC__ASSERT(0 != *block);
492         FLAC__ASSERT((*block)->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
493
494         return 0;
495 }
496
497 static const char *store_to_file_post_(const char *filename, FLAC__Metadata_Chain *chain, FLAC__bool preserve_modtime)
498 {
499         struct stat stats;
500         const FLAC__bool have_stats = get_file_stats_(filename, &stats);
501
502         (void)grabbag__file_change_stats(filename, /*read_only=*/false);
503
504         FLAC__metadata_chain_sort_padding(chain);
505         if(!FLAC__metadata_chain_write(chain, /*use_padding=*/true, preserve_modtime)) {
506                 FLAC__metadata_chain_delete(chain);
507                 return FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(chain)];
508         }
509
510         FLAC__metadata_chain_delete(chain);
511
512         if(have_stats)
513                 set_file_stats_(filename, &stats);
514
515         return 0;
516 }
517
518 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)
519 {
520         FLAC__Metadata_Chain *chain;
521         FLAC__StreamMetadata *block;
522         const char *error;
523
524         if(0 != (error = store_to_file_pre_(filename, &chain, &block)))
525                 return error;
526
527         if(0 != (error = grabbag__replaygain_store_to_vorbiscomment(block, album_gain, album_peak, title_gain, title_peak))) {
528                 FLAC__metadata_chain_delete(chain);
529                 return error;
530         }
531
532         if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime)))
533                 return error;
534
535         return 0;
536 }
537
538 const char *grabbag__replaygain_store_to_file_reference(const char *filename, FLAC__bool preserve_modtime)
539 {
540         FLAC__Metadata_Chain *chain;
541         FLAC__StreamMetadata *block;
542         const char *error;
543
544         if(0 != (error = store_to_file_pre_(filename, &chain, &block)))
545                 return error;
546
547         if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_reference(block))) {
548                 FLAC__metadata_chain_delete(chain);
549                 return error;
550         }
551
552         if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime)))
553                 return error;
554
555         return 0;
556 }
557
558 const char *grabbag__replaygain_store_to_file_album(const char *filename, float album_gain, float album_peak, FLAC__bool preserve_modtime)
559 {
560         FLAC__Metadata_Chain *chain;
561         FLAC__StreamMetadata *block;
562         const char *error;
563
564         if(0 != (error = store_to_file_pre_(filename, &chain, &block)))
565                 return error;
566
567         if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_album(block, album_gain, album_peak))) {
568                 FLAC__metadata_chain_delete(chain);
569                 return error;
570         }
571
572         if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime)))
573                 return error;
574
575         return 0;
576 }
577
578 const char *grabbag__replaygain_store_to_file_title(const char *filename, float title_gain, float title_peak, FLAC__bool preserve_modtime)
579 {
580         FLAC__Metadata_Chain *chain;
581         FLAC__StreamMetadata *block;
582         const char *error;
583
584         if(0 != (error = store_to_file_pre_(filename, &chain, &block)))
585                 return error;
586
587         if(0 != (error = grabbag__replaygain_store_to_vorbiscomment_title(block, title_gain, title_peak))) {
588                 FLAC__metadata_chain_delete(chain);
589                 return error;
590         }
591
592         if(0 != (error = store_to_file_post_(filename, chain, preserve_modtime)))
593                 return error;
594
595         return 0;
596 }
597
598 static FLAC__bool parse_double_(const FLAC__StreamMetadata_VorbisComment_Entry *entry, double *val)
599 {
600         char s[32], *end;
601         const char *p, *q;
602         double v;
603
604         FLAC__ASSERT(0 != entry);
605         FLAC__ASSERT(0 != val);
606
607         p = (const char *)entry->entry;
608         q = strchr(p, '=');
609         if(0 == q)
610                 return false;
611         q++;
612         memset(s, 0, sizeof(s)-1);
613         strncpy(s, q, local_min(sizeof(s)-1, entry->length - (q-p)));
614
615         v = strtod(s, &end);
616         if(end == s)
617                 return false;
618
619         *val = v;
620         return true;
621 }
622
623 FLAC__bool grabbag__replaygain_load_from_vorbiscomment(const FLAC__StreamMetadata *block, FLAC__bool album_mode, FLAC__bool strict, double *reference, double *gain, double *peak)
624 {
625         int reference_offset, gain_offset, peak_offset;
626
627         FLAC__ASSERT(0 != block);
628         FLAC__ASSERT(0 != reference);
629         FLAC__ASSERT(0 != gain);
630         FLAC__ASSERT(0 != peak);
631         FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
632
633         /* Default to current level until overridden by a detected tag; this
634          * will always be true until we change replaygain_analysis.c
635          */
636         *reference = ReplayGainReferenceLoudness;
637
638         if(0 <= (reference_offset = FLAC__metadata_object_vorbiscomment_find_entry_from(block, /*offset=*/0, (const char *)GRABBAG__REPLAYGAIN_TAG_REFERENCE_LOUDNESS)))
639                 (void)parse_double_(block->data.vorbis_comment.comments + reference_offset, reference);
640
641         if(0 > (gain_offset = FLAC__metadata_object_vorbiscomment_find_entry_from(block, /*offset=*/0, (const char *)(album_mode? GRABBAG__REPLAYGAIN_TAG_ALBUM_GAIN : GRABBAG__REPLAYGAIN_TAG_TITLE_GAIN))))
642                 return !strict && grabbag__replaygain_load_from_vorbiscomment(block, !album_mode, /*strict=*/true, reference, gain, peak);
643         if(0 > (peak_offset = FLAC__metadata_object_vorbiscomment_find_entry_from(block, /*offset=*/0, (const char *)(album_mode? GRABBAG__REPLAYGAIN_TAG_ALBUM_PEAK : GRABBAG__REPLAYGAIN_TAG_TITLE_PEAK))))
644                 return !strict && grabbag__replaygain_load_from_vorbiscomment(block, !album_mode, /*strict=*/true, reference, gain, peak);
645
646         if(!parse_double_(block->data.vorbis_comment.comments + gain_offset, gain))
647                 return !strict && grabbag__replaygain_load_from_vorbiscomment(block, !album_mode, /*strict=*/true, reference, gain, peak);
648         if(!parse_double_(block->data.vorbis_comment.comments + peak_offset, peak))
649                 return !strict && grabbag__replaygain_load_from_vorbiscomment(block, !album_mode, /*strict=*/true, reference, gain, peak);
650
651         return true;
652 }
653
654 double grabbag__replaygain_compute_scale_factor(double peak, double gain, double preamp, FLAC__bool prevent_clipping)
655 {
656         double scale;
657         FLAC__ASSERT(peak >= 0.0);
658         gain += preamp;
659         scale = (float) pow(10.0, gain * 0.05);
660         if(prevent_clipping && peak > 0.0) {
661                 const double max_scale = (float)(1.0 / peak);
662                 if(scale > max_scale)
663                         scale = max_scale;
664         }
665         return scale;
666 }