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