1/* libxmms-flac - XMMS FLAC input plugin
2 * Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007  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
56extern void FLAC_XMMS__file_info_box(char *filename);
57
58typedef 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
78static void FLAC_XMMS__init(void);
79static int  FLAC_XMMS__is_our_file(char *filename);
80static void FLAC_XMMS__play_file(char *filename);
81static void FLAC_XMMS__stop(void);
82static void FLAC_XMMS__pause(short p);
83static void FLAC_XMMS__seek(int time);
84static int  FLAC_XMMS__get_time(void);
85static void FLAC_XMMS__cleanup(void);
86static void FLAC_XMMS__get_song_info(char *filename, char **title, int *length);
87
88static void *play_loop_(void *arg);
89
90static FLAC__bool safe_decoder_init_(const char *filename, FLAC__StreamDecoder *decoder);
91static void safe_decoder_finish_(FLAC__StreamDecoder *decoder);
92static void safe_decoder_delete_(FLAC__StreamDecoder *decoder);
93
94static FLAC__StreamDecoderReadStatus http_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
95static FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
96static void metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
97static void error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
98
99InputPlugin 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))
129static FLAC__byte sample_buffer_[SAMPLE_BUFFER_SIZE];
130static unsigned sample_buffer_first_, sample_buffer_last_;
131
132static FLAC__StreamDecoder *decoder_ = 0;
133static stream_data_struct stream_data_;
134static pthread_t decode_thread_;
135static FLAC__bool audio_error_ = false;
136static 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
141static unsigned bitrate_history_[BITRATE_HIST_SIZE];
142
143
144InputPlugin *get_iplugin_info(void)
145{
146	flac_ip.description = g_strdup_printf("Reference FLAC Player v%s", FLAC__VERSION_STRING);
147	return &flac_ip;
148}
149
150void 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
157static gchar* homedir(void)
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
175static FLAC__bool is_http_source(const char *source)
176{
177	return 0 == strncasecmp(source, "http://", 7);
178}
179
180void FLAC_XMMS__init(void)
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
261int 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
272void 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
346void FLAC_XMMS__stop(void)
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
359void FLAC_XMMS__pause(short p)
360{
361	flac_ip.output->pause(p);
362}
363
364void 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
375int FLAC_XMMS__get_time(void)
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
385void FLAC_XMMS__cleanup(void)
386{
387	safe_decoder_delete_(decoder_);
388	decoder_ = 0;
389}
390
391void 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				if(strlen(errtitle) + 1 + strlen(filename) + 1 + 1 < strlen(filename)) { /* overflow check */
404					*title = NULL;
405				}
406				else {
407					*title = g_malloc(strlen(errtitle) + 1 + strlen(filename) + 1 + 1);
408					sprintf(*title, "%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
434void *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
542FLAC__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
569void 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
577void safe_decoder_delete_(FLAC__StreamDecoder *decoder)
578{
579	if(decoder) {
580		safe_decoder_finish_(decoder);
581		FLAC__stream_decoder_delete(decoder);
582	}
583}
584
585FLAC__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
593FLAC__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
653void 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
678void 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}
685