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