xmms - Fix inline linking problems with old glib
[flac.git] / src / plugin_xmms / plugin.c
1 /* libxmms-flac - XMMS FLAC input plugin
2  * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007,2008,2009  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 along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17  */
18
19 #include "plugin.h"
20
21 #include <limits.h>
22 #include <pthread.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <stdio.h>
26 #include <glib.h>
27 #include <pwd.h>
28 #include <sys/types.h>
29 #include <unistd.h>
30
31 #include <xmms/plugin.h>
32 #include <xmms/util.h>
33 #include <xmms/configfile.h>
34 #include <xmms/titlestring.h>
35
36 #ifdef HAVE_LANGINFO_CODESET
37 #include <langinfo.h>
38 #endif
39
40 #include "FLAC/all.h"
41 #include "plugin_common/all.h"
42 #include "share/grabbag.h"
43 #include "share/replaygain_synthesis.h"
44 #include "configure.h"
45 #include "charset.h"
46 #include "http.h"
47 #include "tag.h"
48
49 #ifdef min
50 #undef min
51 #endif
52 #define min(x,y) ((x)<(y)?(x):(y))
53
54 extern void FLAC_XMMS__file_info_box(char *filename);
55
56 typedef struct {
57         FLAC__bool abort_flag;
58         FLAC__bool is_playing;
59         FLAC__bool is_http_source;
60         FLAC__bool eof;
61         FLAC__bool play_thread_open; /* if true, is_playing must also be true */
62         FLAC__uint64 total_samples;
63         unsigned bits_per_sample;
64         unsigned channels;
65         unsigned sample_rate;
66         int length_in_msec; /* int (instead of FLAC__uint64) only because that's what XMMS uses; seeking won't work right if this maxes out */
67         gchar *title;
68         AFormat sample_format;
69         unsigned sample_format_bytes_per_sample;
70         int seek_to_in_sec;
71         FLAC__bool has_replaygain;
72         double replay_scale;
73         DitherContext dither_context;
74 } stream_data_struct;
75
76 static void FLAC_XMMS__init(void);
77 static int  FLAC_XMMS__is_our_file(char *filename);
78 static void FLAC_XMMS__play_file(char *filename);
79 static void FLAC_XMMS__stop(void);
80 static void FLAC_XMMS__pause(short p);
81 static void FLAC_XMMS__seek(int time);
82 static int  FLAC_XMMS__get_time(void);
83 static void FLAC_XMMS__cleanup(void);
84 static void FLAC_XMMS__get_song_info(char *filename, char **title, int *length);
85
86 static void *play_loop_(void *arg);
87
88 static FLAC__bool safe_decoder_init_(const char *filename, FLAC__StreamDecoder *decoder);
89 static void safe_decoder_finish_(FLAC__StreamDecoder *decoder);
90 static void safe_decoder_delete_(FLAC__StreamDecoder *decoder);
91
92 static FLAC__StreamDecoderReadStatus http_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
93 static FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
94 static void metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
95 static void error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
96
97 InputPlugin flac_ip =
98 {
99         NULL,
100         NULL,
101         "FLAC Player v" VERSION,
102         FLAC_XMMS__init,
103         FLAC_XMMS__aboutbox,
104         FLAC_XMMS__configure,
105         FLAC_XMMS__is_our_file,
106         NULL,
107         FLAC_XMMS__play_file,
108         FLAC_XMMS__stop,
109         FLAC_XMMS__pause,
110         FLAC_XMMS__seek,
111         NULL,
112         FLAC_XMMS__get_time,
113         NULL,
114         NULL,
115         FLAC_XMMS__cleanup,
116         NULL,
117         NULL,
118         NULL,
119         NULL,
120         FLAC_XMMS__get_song_info,
121         FLAC_XMMS__file_info_box,
122         NULL
123 };
124
125 #define SAMPLES_PER_WRITE 512
126 #define SAMPLE_BUFFER_SIZE ((FLAC__MAX_BLOCK_SIZE + SAMPLES_PER_WRITE) * FLAC_PLUGIN__MAX_SUPPORTED_CHANNELS * (24/8))
127 static FLAC__byte sample_buffer_[SAMPLE_BUFFER_SIZE];
128 static unsigned sample_buffer_first_, sample_buffer_last_;
129
130 static FLAC__StreamDecoder *decoder_ = 0;
131 static stream_data_struct stream_data_;
132 static pthread_t decode_thread_;
133 static FLAC__bool audio_error_ = false;
134 static FLAC__bool is_big_endian_host_;
135
136 #define BITRATE_HIST_SEGMENT_MSEC 500
137 /* 500ms * 50 = 25s should be enough */
138 #define BITRATE_HIST_SIZE 50
139 static unsigned bitrate_history_[BITRATE_HIST_SIZE];
140
141
142 InputPlugin *get_iplugin_info(void)
143 {
144         flac_ip.description = g_strdup_printf("Reference FLAC Player v%s", FLAC__VERSION_STRING);
145         return &flac_ip;
146 }
147
148 void set_track_info(const char* title, int length_in_msec)
149 {
150         if (stream_data_.is_playing) {
151                 flac_ip.set_info((char*) title, length_in_msec, stream_data_.sample_rate * stream_data_.channels * stream_data_.bits_per_sample, stream_data_.sample_rate, stream_data_.channels);
152         }
153 }
154
155 static gchar* homedir(void)
156 {
157         gchar *result;
158         char *env_home = getenv("HOME");
159         if (env_home) {
160                 result = g_strdup (env_home);
161         } else {
162                 uid_t uid = getuid();
163                 struct passwd *pwent;
164                 do {
165                         pwent = getpwent();
166                 } while (pwent && pwent->pw_uid != uid);
167                 result = pwent ? g_strdup (pwent->pw_dir) : NULL;
168                 endpwent();
169         }
170         return result;
171 }
172
173 static FLAC__bool is_http_source(const char *source)
174 {
175         return 0 == strncasecmp(source, "http://", 7);
176 }
177
178 void FLAC_XMMS__init(void)
179 {
180         ConfigFile *cfg;
181         FLAC__uint32 test = 1;
182
183         is_big_endian_host_ = (*((FLAC__byte*)(&test)))? false : true;
184
185         flac_cfg.title.tag_override = FALSE;
186         if (flac_cfg.title.tag_format)
187                 g_free(flac_cfg.title.tag_format);
188         flac_cfg.title.convert_char_set = FALSE;
189
190         cfg = xmms_cfg_open_default_file();
191
192         /* title */
193
194         xmms_cfg_read_boolean(cfg, "flac", "title.tag_override", &flac_cfg.title.tag_override);
195
196         if(!xmms_cfg_read_string(cfg, "flac", "title.tag_format", &flac_cfg.title.tag_format))
197                 flac_cfg.title.tag_format = g_strdup("%p - %t");
198
199         xmms_cfg_read_boolean(cfg, "flac", "title.convert_char_set", &flac_cfg.title.convert_char_set);
200
201         if(!xmms_cfg_read_string(cfg, "flac", "title.user_char_set", &flac_cfg.title.user_char_set))
202                 flac_cfg.title.user_char_set = FLAC_plugin__charset_get_current();
203
204         /* replaygain */
205
206         xmms_cfg_read_boolean(cfg, "flac", "output.replaygain.enable", &flac_cfg.output.replaygain.enable);
207
208         xmms_cfg_read_boolean(cfg, "flac", "output.replaygain.album_mode", &flac_cfg.output.replaygain.album_mode);
209
210         if(!xmms_cfg_read_int(cfg, "flac", "output.replaygain.preamp", &flac_cfg.output.replaygain.preamp))
211                 flac_cfg.output.replaygain.preamp = 0;
212
213         xmms_cfg_read_boolean(cfg, "flac", "output.replaygain.hard_limit", &flac_cfg.output.replaygain.hard_limit);
214
215         xmms_cfg_read_boolean(cfg, "flac", "output.resolution.normal.dither_24_to_16", &flac_cfg.output.resolution.normal.dither_24_to_16);
216         xmms_cfg_read_boolean(cfg, "flac", "output.resolution.replaygain.dither", &flac_cfg.output.resolution.replaygain.dither);
217
218         if(!xmms_cfg_read_int(cfg, "flac", "output.resolution.replaygain.noise_shaping", &flac_cfg.output.resolution.replaygain.noise_shaping))
219                 flac_cfg.output.resolution.replaygain.noise_shaping = 1;
220
221         if(!xmms_cfg_read_int(cfg, "flac", "output.resolution.replaygain.bps_out", &flac_cfg.output.resolution.replaygain.bps_out))
222                 flac_cfg.output.resolution.replaygain.bps_out = 16;
223
224         /* stream */
225
226         xmms_cfg_read_int(cfg, "flac", "stream.http_buffer_size", &flac_cfg.stream.http_buffer_size);
227         xmms_cfg_read_int(cfg, "flac", "stream.http_prebuffer", &flac_cfg.stream.http_prebuffer);
228         xmms_cfg_read_boolean(cfg, "flac", "stream.use_proxy", &flac_cfg.stream.use_proxy);
229         if(flac_cfg.stream.proxy_host)
230                 g_free(flac_cfg.stream.proxy_host);
231         if(!xmms_cfg_read_string(cfg, "flac", "stream.proxy_host", &flac_cfg.stream.proxy_host))
232                 flac_cfg.stream.proxy_host = g_strdup("");
233         xmms_cfg_read_int(cfg, "flac", "stream.proxy_port", &flac_cfg.stream.proxy_port);
234         xmms_cfg_read_boolean(cfg, "flac", "stream.proxy_use_auth", &flac_cfg.stream.proxy_use_auth);
235         if(flac_cfg.stream.proxy_user)
236                 g_free(flac_cfg.stream.proxy_user);
237         flac_cfg.stream.proxy_user = NULL;
238         xmms_cfg_read_string(cfg, "flac", "stream.proxy_user", &flac_cfg.stream.proxy_user);
239         if(flac_cfg.stream.proxy_pass)
240                 g_free(flac_cfg.stream.proxy_pass);
241         flac_cfg.stream.proxy_pass = NULL;
242         xmms_cfg_read_string(cfg, "flac", "stream.proxy_pass", &flac_cfg.stream.proxy_pass);
243         xmms_cfg_read_boolean(cfg, "flac", "stream.save_http_stream", &flac_cfg.stream.save_http_stream);
244         if (flac_cfg.stream.save_http_path)
245                 g_free (flac_cfg.stream.save_http_path);
246         if (!xmms_cfg_read_string(cfg, "flac", "stream.save_http_path", &flac_cfg.stream.save_http_path) || ! *flac_cfg.stream.save_http_path) {
247                 if (flac_cfg.stream.save_http_path)
248                         g_free (flac_cfg.stream.save_http_path);
249                 flac_cfg.stream.save_http_path = homedir();
250         }
251         xmms_cfg_read_boolean(cfg, "flac", "stream.cast_title_streaming", &flac_cfg.stream.cast_title_streaming);
252         xmms_cfg_read_boolean(cfg, "flac", "stream.use_udp_channel", &flac_cfg.stream.use_udp_channel);
253
254         decoder_ = FLAC__stream_decoder_new();
255
256         xmms_cfg_free(cfg);
257 }
258
259 int FLAC_XMMS__is_our_file(char *filename)
260 {
261         char *ext;
262
263         ext = strrchr(filename, '.');
264         if(ext)
265                 if(!strcasecmp(ext, ".flac") || !strcasecmp(ext, ".fla"))
266                         return 1;
267         return 0;
268 }
269
270 void FLAC_XMMS__play_file(char *filename)
271 {
272         FILE *f;
273
274         sample_buffer_first_ = sample_buffer_last_ = 0;
275         audio_error_ = false;
276         stream_data_.abort_flag = false;
277         stream_data_.is_playing = false;
278         stream_data_.is_http_source = is_http_source(filename);
279         stream_data_.eof = false;
280         stream_data_.play_thread_open = false;
281         stream_data_.has_replaygain = false;
282
283         if(!is_http_source(filename)) {
284                 if(0 == (f = fopen(filename, "r")))
285                         return;
286                 fclose(f);
287         }
288
289         if(decoder_ == 0)
290                 return;
291
292         if(!safe_decoder_init_(filename, decoder_))
293                 return;
294
295         if(stream_data_.has_replaygain && flac_cfg.output.replaygain.enable) {
296                 if(flac_cfg.output.resolution.replaygain.bps_out == 8) {
297                         stream_data_.sample_format = FMT_U8;
298                         stream_data_.sample_format_bytes_per_sample = 1;
299                 }
300                 else if(flac_cfg.output.resolution.replaygain.bps_out == 16) {
301                         stream_data_.sample_format = (is_big_endian_host_) ? FMT_S16_BE : FMT_S16_LE;
302                         stream_data_.sample_format_bytes_per_sample = 2;
303                 }
304                 else {
305                         /*@@@ need some error here like wa2: MessageBox(mod_.hMainWindow, "ERROR: plugin can only handle 8/16-bit samples\n", "ERROR: plugin can only handle 8/16-bit samples", 0); */
306                         fprintf(stderr, "libxmms-flac: can't handle %d bit output\n", flac_cfg.output.resolution.replaygain.bps_out);
307                         safe_decoder_finish_(decoder_);
308                         return;
309                 }
310         }
311         else {
312                 if(stream_data_.bits_per_sample == 8) {
313                         stream_data_.sample_format = FMT_U8;
314                         stream_data_.sample_format_bytes_per_sample = 1;
315                 }
316                 else if(stream_data_.bits_per_sample == 16 || (stream_data_.bits_per_sample == 24 && flac_cfg.output.resolution.normal.dither_24_to_16)) {
317                         stream_data_.sample_format = (is_big_endian_host_) ? FMT_S16_BE : FMT_S16_LE;
318                         stream_data_.sample_format_bytes_per_sample = 2;
319                 }
320                 else {
321                         /*@@@ need some error here like wa2: MessageBox(mod_.hMainWindow, "ERROR: plugin can only handle 8/16-bit samples\n", "ERROR: plugin can only handle 8/16-bit samples", 0); */
322                         fprintf(stderr, "libxmms-flac: can't handle %d bit output\n", stream_data_.bits_per_sample);
323                         safe_decoder_finish_(decoder_);
324                         return;
325                 }
326         }
327         FLAC__replaygain_synthesis__init_dither_context(&stream_data_.dither_context, stream_data_.sample_format_bytes_per_sample * 8, flac_cfg.output.resolution.replaygain.noise_shaping);
328         stream_data_.is_playing = true;
329
330         if(flac_ip.output->open_audio(stream_data_.sample_format, stream_data_.sample_rate, stream_data_.channels) == 0) {
331                 audio_error_ = true;
332                 safe_decoder_finish_(decoder_);
333                 return;
334         }
335
336         stream_data_.title = flac_format_song_title(filename);
337         flac_ip.set_info(stream_data_.title, stream_data_.length_in_msec, stream_data_.sample_rate * stream_data_.channels * stream_data_.bits_per_sample, stream_data_.sample_rate, stream_data_.channels);
338
339         stream_data_.seek_to_in_sec = -1;
340         stream_data_.play_thread_open = true;
341         pthread_create(&decode_thread_, NULL, play_loop_, NULL);
342 }
343
344 void FLAC_XMMS__stop(void)
345 {
346         if(stream_data_.is_playing) {
347                 stream_data_.is_playing = false;
348                 if(stream_data_.play_thread_open) {
349                         stream_data_.play_thread_open = false;
350                         pthread_join(decode_thread_, NULL);
351                 }
352                 flac_ip.output->close_audio();
353                 safe_decoder_finish_(decoder_);
354         }
355 }
356
357 void FLAC_XMMS__pause(short p)
358 {
359         flac_ip.output->pause(p);
360 }
361
362 void FLAC_XMMS__seek(int time)
363 {
364         if(!stream_data_.is_http_source) {
365                 stream_data_.seek_to_in_sec = time;
366                 stream_data_.eof = false;
367
368                 while(stream_data_.seek_to_in_sec != -1)
369                         xmms_usleep(10000);
370         }
371 }
372
373 int FLAC_XMMS__get_time(void)
374 {
375         if(audio_error_)
376                 return -2;
377         if(!stream_data_.is_playing || (stream_data_.eof && !flac_ip.output->buffer_playing()))
378                 return -1;
379         else
380                 return flac_ip.output->output_time();
381 }
382
383 void FLAC_XMMS__cleanup(void)
384 {
385         safe_decoder_delete_(decoder_);
386         decoder_ = 0;
387 }
388
389 void FLAC_XMMS__get_song_info(char *filename, char **title, int *length_in_msec)
390 {
391         FLAC__StreamMetadata streaminfo;
392
393         if(0 == filename)
394                 filename = "";
395
396         if(!FLAC__metadata_get_streaminfo(filename, &streaminfo)) {
397                 /* @@@ how to report the error? */
398                 if(title) {
399                         if (!is_http_source(filename)) {
400                                 static const char *errtitle = "Invalid FLAC File: ";
401                                 if(strlen(errtitle) + 1 + strlen(filename) + 1 + 1 < strlen(filename)) { /* overflow check */
402                                         *title = NULL;
403                                 }
404                                 else {
405                                         *title = g_malloc(strlen(errtitle) + 1 + strlen(filename) + 1 + 1);
406                                         sprintf(*title, "%s\"%s\"", errtitle, filename);
407                                 }
408                         } else {
409                                 *title = NULL;
410                         }
411                 }
412                 if(length_in_msec)
413                         *length_in_msec = -1;
414                 return;
415         }
416
417         if(title) {
418                 *title = flac_format_song_title(filename);
419         }
420         if(length_in_msec) {
421                 FLAC__uint64 l = (FLAC__uint64)((double)streaminfo.data.stream_info.total_samples / (double)streaminfo.data.stream_info.sample_rate * 1000.0 + 0.5);
422                 if (l > INT_MAX)
423                         l = INT_MAX;
424                 *length_in_msec = (int)l;
425         }
426 }
427
428 /***********************************************************************
429  * local routines
430  **********************************************************************/
431
432 void *play_loop_(void *arg)
433 {
434         unsigned written_time_last = 0, bh_index_last_w = 0, bh_index_last_o = BITRATE_HIST_SIZE, blocksize = 1;
435         FLAC__uint64 decode_position_last = 0, decode_position_frame_last = 0, decode_position_frame = 0;
436
437         (void)arg;
438
439         while(stream_data_.is_playing) {
440                 if(!stream_data_.eof) {
441                         while(sample_buffer_last_ - sample_buffer_first_ < SAMPLES_PER_WRITE) {
442                                 unsigned s;
443
444                                 s = sample_buffer_last_ - sample_buffer_first_;
445                                 if(FLAC__stream_decoder_get_state(decoder_) == FLAC__STREAM_DECODER_END_OF_STREAM) {
446                                         stream_data_.eof = true;
447                                         break;
448                                 }
449                                 else if(!FLAC__stream_decoder_process_single(decoder_)) {
450                                         /*@@@ this should probably be a dialog */
451                                         fprintf(stderr, "libxmms-flac: READ ERROR processing frame\n");
452                                         stream_data_.eof = true;
453                                         break;
454                                 }
455                                 blocksize = sample_buffer_last_ - sample_buffer_first_ - s;
456                                 decode_position_frame_last = decode_position_frame;
457                                 if(stream_data_.is_http_source || !FLAC__stream_decoder_get_decode_position(decoder_, &decode_position_frame))
458                                         decode_position_frame = 0;
459                         }
460                         if(sample_buffer_last_ - sample_buffer_first_ > 0) {
461                                 const unsigned n = min(sample_buffer_last_ - sample_buffer_first_, SAMPLES_PER_WRITE);
462                                 int bytes = n * stream_data_.channels * stream_data_.sample_format_bytes_per_sample;
463                                 FLAC__byte *sample_buffer_start = sample_buffer_ + sample_buffer_first_ * stream_data_.channels * stream_data_.sample_format_bytes_per_sample;
464                                 unsigned written_time, bh_index_w;
465                                 FLAC__uint64 decode_position;
466
467                                 sample_buffer_first_ += n;
468                                 flac_ip.add_vis_pcm(flac_ip.output->written_time(), stream_data_.sample_format, stream_data_.channels, bytes, sample_buffer_start);
469                                 while(flac_ip.output->buffer_free() < (int)bytes && stream_data_.is_playing && stream_data_.seek_to_in_sec == -1)
470                                         xmms_usleep(10000);
471                                 if(stream_data_.is_playing && stream_data_.seek_to_in_sec == -1)
472                                         flac_ip.output->write_audio(sample_buffer_start, bytes);
473
474                                 /* compute current bitrate */
475
476                                 written_time = flac_ip.output->written_time();
477                                 bh_index_w = written_time / BITRATE_HIST_SEGMENT_MSEC % BITRATE_HIST_SIZE;
478                                 if(bh_index_w != bh_index_last_w) {
479                                         bh_index_last_w = bh_index_w;
480                                         decode_position = decode_position_frame - (double)(sample_buffer_last_ - sample_buffer_first_) * (double)(decode_position_frame - decode_position_frame_last) / (double)blocksize;
481                                         bitrate_history_[(bh_index_w + BITRATE_HIST_SIZE - 1) % BITRATE_HIST_SIZE] =
482                                                 decode_position > decode_position_last && written_time > written_time_last ?
483                                                         8000 * (decode_position - decode_position_last) / (written_time - written_time_last) :
484                                                         stream_data_.sample_rate * stream_data_.channels * stream_data_.bits_per_sample;
485                                         decode_position_last = decode_position;
486                                         written_time_last = written_time;
487                                 }
488                         }
489                         else {
490                                 stream_data_.eof = true;
491                                 xmms_usleep(10000);
492                         }
493                 }
494                 else
495                         xmms_usleep(10000);
496                 if(!stream_data_.is_http_source && stream_data_.seek_to_in_sec != -1) {
497                         const double distance = (double)stream_data_.seek_to_in_sec * 1000.0 / (double)stream_data_.length_in_msec;
498                         FLAC__uint64 target_sample = (FLAC__uint64)(distance * (double)stream_data_.total_samples);
499                         if(stream_data_.total_samples > 0 && target_sample >= stream_data_.total_samples)
500                                 target_sample = stream_data_.total_samples - 1;
501                         if(FLAC__stream_decoder_seek_absolute(decoder_, target_sample)) {
502                                 flac_ip.output->flush(stream_data_.seek_to_in_sec * 1000);
503                                 bh_index_last_w = bh_index_last_o = flac_ip.output->output_time() / BITRATE_HIST_SEGMENT_MSEC % BITRATE_HIST_SIZE;
504                                 if(!FLAC__stream_decoder_get_decode_position(decoder_, &decode_position_frame))
505                                         decode_position_frame = 0;
506                                 stream_data_.eof = false;
507                                 sample_buffer_first_ = sample_buffer_last_ = 0;
508                         }
509                         else if(FLAC__stream_decoder_get_state(decoder_) == FLAC__STREAM_DECODER_SEEK_ERROR) {
510                                 /*@@@ this should probably be a dialog */
511                                 fprintf(stderr, "libxmms-flac: SEEK ERROR\n");
512                                 FLAC__stream_decoder_flush(decoder_);
513                                 stream_data_.eof = false;
514                                 sample_buffer_first_ = sample_buffer_last_ = 0;
515                         }
516                         stream_data_.seek_to_in_sec = -1;
517                 }
518                 else {
519                         /* display the right bitrate from history */
520                         unsigned bh_index_o = flac_ip.output->output_time() / BITRATE_HIST_SEGMENT_MSEC % BITRATE_HIST_SIZE;
521                         if(bh_index_o != bh_index_last_o && bh_index_o != bh_index_last_w && bh_index_o != (bh_index_last_w + 1) % BITRATE_HIST_SIZE) {
522                                 bh_index_last_o = bh_index_o;
523                                 flac_ip.set_info(stream_data_.title, stream_data_.length_in_msec, bitrate_history_[bh_index_o], stream_data_.sample_rate, stream_data_.channels);
524                         }
525                 }
526         }
527
528         safe_decoder_finish_(decoder_);
529
530         /* are these two calls necessary? */
531         flac_ip.output->buffer_free();
532         flac_ip.output->buffer_free();
533
534         g_free(stream_data_.title);
535
536         pthread_exit(NULL);
537         return 0; /* to silence the compiler warning about not returning a value */
538 }
539
540 FLAC__bool safe_decoder_init_(const char *filename, FLAC__StreamDecoder *decoder)
541 {
542         if(decoder == 0)
543                 return false;
544
545         safe_decoder_finish_(decoder);
546
547         FLAC__stream_decoder_set_md5_checking(decoder, false);
548         FLAC__stream_decoder_set_metadata_ignore_all(decoder);
549         FLAC__stream_decoder_set_metadata_respond(decoder, FLAC__METADATA_TYPE_STREAMINFO);
550         FLAC__stream_decoder_set_metadata_respond(decoder, FLAC__METADATA_TYPE_VORBIS_COMMENT);
551         if(stream_data_.is_http_source) {
552                 flac_http_open(filename, 0);
553                 if(FLAC__stream_decoder_init_stream(decoder, http_read_callback_, /*seek_callback=*/0, /*tell_callback=*/0, /*length_callback=*/0, /*eof_callback=*/0, write_callback_, metadata_callback_, error_callback_, /*client_data=*/&stream_data_) != FLAC__STREAM_DECODER_INIT_STATUS_OK)
554                         return false;
555         }
556         else {
557                 if(FLAC__stream_decoder_init_file(decoder, filename, write_callback_, metadata_callback_, error_callback_, /*client_data=*/&stream_data_) != FLAC__STREAM_DECODER_INIT_STATUS_OK)
558                         return false;
559         }
560
561         if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder))
562                 return false;
563
564         return true;
565 }
566
567 void safe_decoder_finish_(FLAC__StreamDecoder *decoder)
568 {
569         if(decoder && FLAC__stream_decoder_get_state(decoder) != FLAC__STREAM_DECODER_UNINITIALIZED)
570                 (void)FLAC__stream_decoder_finish(decoder);
571         if(stream_data_.is_http_source)
572                 flac_http_close();
573 }
574
575 void safe_decoder_delete_(FLAC__StreamDecoder *decoder)
576 {
577         if(decoder) {
578                 safe_decoder_finish_(decoder);
579                 FLAC__stream_decoder_delete(decoder);
580         }
581 }
582
583 FLAC__StreamDecoderReadStatus http_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
584 {
585         (void)decoder;
586         (void)client_data;
587         *bytes = flac_http_read(buffer, *bytes);
588         return *bytes ? FLAC__STREAM_DECODER_READ_STATUS_CONTINUE : FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
589 }
590
591 FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
592 {
593         stream_data_struct *stream_data = (stream_data_struct *)client_data;
594         const unsigned channels = stream_data->channels, wide_samples = frame->header.blocksize;
595         const unsigned bits_per_sample = stream_data->bits_per_sample;
596         FLAC__byte *sample_buffer_start;
597
598         (void)decoder;
599
600         if(stream_data->abort_flag)
601                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
602
603         if((sample_buffer_last_ + wide_samples) > (SAMPLE_BUFFER_SIZE / (channels * stream_data->sample_format_bytes_per_sample))) {
604                 memmove(sample_buffer_, sample_buffer_ + sample_buffer_first_ * channels * stream_data->sample_format_bytes_per_sample, (sample_buffer_last_ - sample_buffer_first_) * channels * stream_data->sample_format_bytes_per_sample);
605                 sample_buffer_last_ -= sample_buffer_first_;
606                 sample_buffer_first_ = 0;
607         }
608         sample_buffer_start = sample_buffer_ + sample_buffer_last_ * channels * stream_data->sample_format_bytes_per_sample;
609         if(stream_data->has_replaygain && flac_cfg.output.replaygain.enable) {
610                 FLAC__replaygain_synthesis__apply_gain(
611                                 sample_buffer_start,
612                                 !is_big_endian_host_,
613                                 stream_data->sample_format_bytes_per_sample == 1, /* unsigned_data_out */
614                                 buffer,
615                                 wide_samples,
616                                 channels,
617                                 bits_per_sample,
618                                 stream_data->sample_format_bytes_per_sample * 8,
619                                 stream_data->replay_scale,
620                                 flac_cfg.output.replaygain.hard_limit,
621                                 flac_cfg.output.resolution.replaygain.dither,
622                                 &stream_data->dither_context
623                 );
624         }
625         else if(is_big_endian_host_) {
626                 FLAC__plugin_common__pack_pcm_signed_big_endian(
627                         sample_buffer_start,
628                         buffer,
629                         wide_samples,
630                         channels,
631                         bits_per_sample,
632                         stream_data->sample_format_bytes_per_sample * 8
633                 );
634         }
635         else {
636                 FLAC__plugin_common__pack_pcm_signed_little_endian(
637                         sample_buffer_start,
638                         buffer,
639                         wide_samples,
640                         channels,
641                         bits_per_sample,
642                         stream_data->sample_format_bytes_per_sample * 8
643                 );
644         }
645
646         sample_buffer_last_ += wide_samples;
647
648         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
649 }
650
651 void metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
652 {
653         stream_data_struct *stream_data = (stream_data_struct *)client_data;
654         (void)decoder;
655         if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
656                 stream_data->total_samples = metadata->data.stream_info.total_samples;
657                 stream_data->bits_per_sample = metadata->data.stream_info.bits_per_sample;
658                 stream_data->channels = metadata->data.stream_info.channels;
659                 stream_data->sample_rate = metadata->data.stream_info.sample_rate;
660                 {
661                         FLAC__uint64 l = (FLAC__uint64)((double)stream_data->total_samples / (double)stream_data->sample_rate * 1000.0 + 0.5);
662                         if (l > INT_MAX)
663                                 l = INT_MAX;
664                         stream_data->length_in_msec = (int)l;
665                 }
666         }
667         else if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
668                 double reference, gain, peak;
669                 if(grabbag__replaygain_load_from_vorbiscomment(metadata, flac_cfg.output.replaygain.album_mode, /*strict=*/false, &reference, &gain, &peak)) {
670                         stream_data->has_replaygain = true;
671                         stream_data->replay_scale = grabbag__replaygain_compute_scale_factor(peak, gain, (double)flac_cfg.output.replaygain.preamp, /*prevent_clipping=*/!flac_cfg.output.replaygain.hard_limit);
672                 }
673         }
674 }
675
676 void error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
677 {
678         stream_data_struct *stream_data = (stream_data_struct *)client_data;
679         (void)decoder;
680         if(status != FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC)
681                 stream_data->abort_flag = true;
682 }