Use new function flac_snprintf() where ever appropriate.
[platform/upstream/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                                         size_t len = strlen(errtitle) + 1 + strlen(filename) + 1 + 1;
406                                         *title = g_malloc(len);
407                                         flac_snprintf(*title, len, "%s\"%s\"", errtitle, filename);
408                                 }
409                         } else {
410                                 *title = NULL;
411                         }
412                 }
413                 if(length_in_msec)
414                         *length_in_msec = -1;
415                 return;
416         }
417
418         if(title) {
419                 *title = flac_format_song_title(filename);
420         }
421         if(length_in_msec) {
422                 FLAC__uint64 l = (FLAC__uint64)((double)streaminfo.data.stream_info.total_samples / (double)streaminfo.data.stream_info.sample_rate * 1000.0 + 0.5);
423                 if (l > INT_MAX)
424                         l = INT_MAX;
425                 *length_in_msec = (int)l;
426         }
427 }
428
429 /***********************************************************************
430  * local routines
431  **********************************************************************/
432
433 void *play_loop_(void *arg)
434 {
435         unsigned written_time_last = 0, bh_index_last_w = 0, bh_index_last_o = BITRATE_HIST_SIZE, blocksize = 1;
436         FLAC__uint64 decode_position_last = 0, decode_position_frame_last = 0, decode_position_frame = 0;
437
438         (void)arg;
439
440         while(stream_data_.is_playing) {
441                 if(!stream_data_.eof) {
442                         while(sample_buffer_last_ - sample_buffer_first_ < SAMPLES_PER_WRITE) {
443                                 unsigned s;
444
445                                 s = sample_buffer_last_ - sample_buffer_first_;
446                                 if(FLAC__stream_decoder_get_state(decoder_) == FLAC__STREAM_DECODER_END_OF_STREAM) {
447                                         stream_data_.eof = true;
448                                         break;
449                                 }
450                                 else if(!FLAC__stream_decoder_process_single(decoder_)) {
451                                         /*@@@ this should probably be a dialog */
452                                         fprintf(stderr, "libxmms-flac: READ ERROR processing frame\n");
453                                         stream_data_.eof = true;
454                                         break;
455                                 }
456                                 blocksize = sample_buffer_last_ - sample_buffer_first_ - s;
457                                 decode_position_frame_last = decode_position_frame;
458                                 if(stream_data_.is_http_source || !FLAC__stream_decoder_get_decode_position(decoder_, &decode_position_frame))
459                                         decode_position_frame = 0;
460                         }
461                         if(sample_buffer_last_ - sample_buffer_first_ > 0) {
462                                 const unsigned n = min(sample_buffer_last_ - sample_buffer_first_, SAMPLES_PER_WRITE);
463                                 int bytes = n * stream_data_.channels * stream_data_.sample_format_bytes_per_sample;
464                                 FLAC__byte *sample_buffer_start = sample_buffer_ + sample_buffer_first_ * stream_data_.channels * stream_data_.sample_format_bytes_per_sample;
465                                 unsigned written_time, bh_index_w;
466                                 FLAC__uint64 decode_position;
467
468                                 sample_buffer_first_ += n;
469                                 flac_ip.add_vis_pcm(flac_ip.output->written_time(), stream_data_.sample_format, stream_data_.channels, bytes, sample_buffer_start);
470                                 while(flac_ip.output->buffer_free() < (int)bytes && stream_data_.is_playing && stream_data_.seek_to_in_sec == -1)
471                                         xmms_usleep(10000);
472                                 if(stream_data_.is_playing && stream_data_.seek_to_in_sec == -1)
473                                         flac_ip.output->write_audio(sample_buffer_start, bytes);
474
475                                 /* compute current bitrate */
476
477                                 written_time = flac_ip.output->written_time();
478                                 bh_index_w = written_time / BITRATE_HIST_SEGMENT_MSEC % BITRATE_HIST_SIZE;
479                                 if(bh_index_w != bh_index_last_w) {
480                                         bh_index_last_w = bh_index_w;
481                                         decode_position = decode_position_frame - (double)(sample_buffer_last_ - sample_buffer_first_) * (double)(decode_position_frame - decode_position_frame_last) / (double)blocksize;
482                                         bitrate_history_[(bh_index_w + BITRATE_HIST_SIZE - 1) % BITRATE_HIST_SIZE] =
483                                                 decode_position > decode_position_last && written_time > written_time_last ?
484                                                         8000 * (decode_position - decode_position_last) / (written_time - written_time_last) :
485                                                         stream_data_.sample_rate * stream_data_.channels * stream_data_.bits_per_sample;
486                                         decode_position_last = decode_position;
487                                         written_time_last = written_time;
488                                 }
489                         }
490                         else {
491                                 stream_data_.eof = true;
492                                 xmms_usleep(10000);
493                         }
494                 }
495                 else
496                         xmms_usleep(10000);
497                 if(!stream_data_.is_http_source && stream_data_.seek_to_in_sec != -1) {
498                         const double distance = (double)stream_data_.seek_to_in_sec * 1000.0 / (double)stream_data_.length_in_msec;
499                         FLAC__uint64 target_sample = (FLAC__uint64)(distance * (double)stream_data_.total_samples);
500                         if(stream_data_.total_samples > 0 && target_sample >= stream_data_.total_samples)
501                                 target_sample = stream_data_.total_samples - 1;
502                         if(FLAC__stream_decoder_seek_absolute(decoder_, target_sample)) {
503                                 flac_ip.output->flush(stream_data_.seek_to_in_sec * 1000);
504                                 bh_index_last_w = bh_index_last_o = flac_ip.output->output_time() / BITRATE_HIST_SEGMENT_MSEC % BITRATE_HIST_SIZE;
505                                 if(!FLAC__stream_decoder_get_decode_position(decoder_, &decode_position_frame))
506                                         decode_position_frame = 0;
507                                 stream_data_.eof = false;
508                                 sample_buffer_first_ = sample_buffer_last_ = 0;
509                         }
510                         else if(FLAC__stream_decoder_get_state(decoder_) == FLAC__STREAM_DECODER_SEEK_ERROR) {
511                                 /*@@@ this should probably be a dialog */
512                                 fprintf(stderr, "libxmms-flac: SEEK ERROR\n");
513                                 FLAC__stream_decoder_flush(decoder_);
514                                 stream_data_.eof = false;
515                                 sample_buffer_first_ = sample_buffer_last_ = 0;
516                         }
517                         stream_data_.seek_to_in_sec = -1;
518                 }
519                 else {
520                         /* display the right bitrate from history */
521                         unsigned bh_index_o = flac_ip.output->output_time() / BITRATE_HIST_SEGMENT_MSEC % BITRATE_HIST_SIZE;
522                         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) {
523                                 bh_index_last_o = bh_index_o;
524                                 flac_ip.set_info(stream_data_.title, stream_data_.length_in_msec, bitrate_history_[bh_index_o], stream_data_.sample_rate, stream_data_.channels);
525                         }
526                 }
527         }
528
529         safe_decoder_finish_(decoder_);
530
531         /* are these two calls necessary? */
532         flac_ip.output->buffer_free();
533         flac_ip.output->buffer_free();
534
535         g_free(stream_data_.title);
536
537         pthread_exit(NULL);
538         return 0; /* to silence the compiler warning about not returning a value */
539 }
540
541 FLAC__bool safe_decoder_init_(const char *filename, FLAC__StreamDecoder *decoder)
542 {
543         if(decoder == 0)
544                 return false;
545
546         safe_decoder_finish_(decoder);
547
548         FLAC__stream_decoder_set_md5_checking(decoder, false);
549         FLAC__stream_decoder_set_metadata_ignore_all(decoder);
550         FLAC__stream_decoder_set_metadata_respond(decoder, FLAC__METADATA_TYPE_STREAMINFO);
551         FLAC__stream_decoder_set_metadata_respond(decoder, FLAC__METADATA_TYPE_VORBIS_COMMENT);
552         if(stream_data_.is_http_source) {
553                 flac_http_open(filename, 0);
554                 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)
555                         return false;
556         }
557         else {
558                 if(FLAC__stream_decoder_init_file(decoder, filename, write_callback_, metadata_callback_, error_callback_, /*client_data=*/&stream_data_) != FLAC__STREAM_DECODER_INIT_STATUS_OK)
559                         return false;
560         }
561
562         if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder))
563                 return false;
564
565         return true;
566 }
567
568 void safe_decoder_finish_(FLAC__StreamDecoder *decoder)
569 {
570         if(decoder && FLAC__stream_decoder_get_state(decoder) != FLAC__STREAM_DECODER_UNINITIALIZED)
571                 (void)FLAC__stream_decoder_finish(decoder);
572         if(stream_data_.is_http_source)
573                 flac_http_close();
574 }
575
576 void safe_decoder_delete_(FLAC__StreamDecoder *decoder)
577 {
578         if(decoder) {
579                 safe_decoder_finish_(decoder);
580                 FLAC__stream_decoder_delete(decoder);
581         }
582 }
583
584 FLAC__StreamDecoderReadStatus http_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
585 {
586         (void)decoder;
587         (void)client_data;
588         *bytes = flac_http_read(buffer, *bytes);
589         return *bytes ? FLAC__STREAM_DECODER_READ_STATUS_CONTINUE : FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
590 }
591
592 FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
593 {
594         stream_data_struct *stream_data = (stream_data_struct *)client_data;
595         const unsigned channels = stream_data->channels, wide_samples = frame->header.blocksize;
596         const unsigned bits_per_sample = stream_data->bits_per_sample;
597         FLAC__byte *sample_buffer_start;
598
599         (void)decoder;
600
601         if(stream_data->abort_flag)
602                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
603
604         if((sample_buffer_last_ + wide_samples) > (SAMPLE_BUFFER_SIZE / (channels * stream_data->sample_format_bytes_per_sample))) {
605                 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);
606                 sample_buffer_last_ -= sample_buffer_first_;
607                 sample_buffer_first_ = 0;
608         }
609         sample_buffer_start = sample_buffer_ + sample_buffer_last_ * channels * stream_data->sample_format_bytes_per_sample;
610         if(stream_data->has_replaygain && flac_cfg.output.replaygain.enable) {
611                 FLAC__replaygain_synthesis__apply_gain(
612                                 sample_buffer_start,
613                                 !is_big_endian_host_,
614                                 stream_data->sample_format_bytes_per_sample == 1, /* unsigned_data_out */
615                                 buffer,
616                                 wide_samples,
617                                 channels,
618                                 bits_per_sample,
619                                 stream_data->sample_format_bytes_per_sample * 8,
620                                 stream_data->replay_scale,
621                                 flac_cfg.output.replaygain.hard_limit,
622                                 flac_cfg.output.resolution.replaygain.dither,
623                                 &stream_data->dither_context
624                 );
625         }
626         else if(is_big_endian_host_) {
627                 FLAC__plugin_common__pack_pcm_signed_big_endian(
628                         sample_buffer_start,
629                         buffer,
630                         wide_samples,
631                         channels,
632                         bits_per_sample,
633                         stream_data->sample_format_bytes_per_sample * 8
634                 );
635         }
636         else {
637                 FLAC__plugin_common__pack_pcm_signed_little_endian(
638                         sample_buffer_start,
639                         buffer,
640                         wide_samples,
641                         channels,
642                         bits_per_sample,
643                         stream_data->sample_format_bytes_per_sample * 8
644                 );
645         }
646
647         sample_buffer_last_ += wide_samples;
648
649         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
650 }
651
652 void metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
653 {
654         stream_data_struct *stream_data = (stream_data_struct *)client_data;
655         (void)decoder;
656         if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
657                 stream_data->total_samples = metadata->data.stream_info.total_samples;
658                 stream_data->bits_per_sample = metadata->data.stream_info.bits_per_sample;
659                 stream_data->channels = metadata->data.stream_info.channels;
660                 stream_data->sample_rate = metadata->data.stream_info.sample_rate;
661                 {
662                         FLAC__uint64 l = (FLAC__uint64)((double)stream_data->total_samples / (double)stream_data->sample_rate * 1000.0 + 0.5);
663                         if (l > INT_MAX)
664                                 l = INT_MAX;
665                         stream_data->length_in_msec = (int)l;
666                 }
667         }
668         else if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
669                 double reference, gain, peak;
670                 if(grabbag__replaygain_load_from_vorbiscomment(metadata, flac_cfg.output.replaygain.album_mode, /*strict=*/false, &reference, &gain, &peak)) {
671                         stream_data->has_replaygain = true;
672                         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);
673                 }
674         }
675 }
676
677 void error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
678 {
679         stream_data_struct *stream_data = (stream_data_struct *)client_data;
680         (void)decoder;
681         if(status != FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC)
682                 stream_data->abort_flag = true;
683 }