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