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