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