finish replaygain implementation + config tab
[flac.git] / src / plugin_xmms / plugin.c
1 /* libxmms-flac - XMMS FLAC input plugin
2  * Copyright (C) 2000,2001,2002  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 #include <pthread.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <stdio.h>
23 #include <glib.h>
24
25 #include <xmms/plugin.h>
26 #include <xmms/util.h>
27 #include <xmms/configfile.h>
28 #include <xmms/titlestring.h>
29
30 #ifdef HAVE_CONFIG_H
31 #include <config.h>
32 #endif
33
34 #ifdef HAVE_LANGINFO_CODESET
35 #include <langinfo.h>
36 #endif
37
38 #include "FLAC/all.h"
39 #include "plugin_common/all.h"
40 #include "share/replaygain.h"
41 #include "configure.h"
42 #include "wrap_id3.h"
43 #include "charset.h"
44
45 #ifdef min
46 #undef min
47 #endif
48 #define min(x,y) ((x)<(y)?(x):(y))
49
50
51 typedef struct {
52         FLAC__bool abort_flag;
53         FLAC__bool is_playing;
54         FLAC__bool eof;
55         FLAC__bool play_thread_open; /* if true, is_playing must also be true */
56         unsigned total_samples;
57         unsigned bits_per_sample;
58         unsigned channels;
59         unsigned sample_rate;
60         unsigned length_in_msec;
61         AFormat sample_format;
62         int seek_to_in_sec;
63         FLAC__bool has_replaygain;
64         double replay_scale;
65         DitherContext dither_context;
66 } file_info_struct;
67
68 static void FLAC_XMMS__init();
69 static int  FLAC_XMMS__is_our_file(char *filename);
70 static void FLAC_XMMS__play_file(char *filename);
71 static void FLAC_XMMS__stop();
72 static void FLAC_XMMS__pause(short p);
73 static void FLAC_XMMS__seek(int time);
74 static int  FLAC_XMMS__get_time();
75 static void FLAC_XMMS__cleanup();
76 static void FLAC_XMMS__get_song_info(char *filename, char **title, int *length);
77
78 static void *play_loop_(void *arg);
79 static FLAC__bool safe_decoder_init_(const char *filename, FLAC__FileDecoder *decoder);
80 static void safe_decoder_finish_(FLAC__FileDecoder *decoder);
81 static void safe_decoder_delete_(FLAC__FileDecoder *decoder);
82 static FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__FileDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
83 static void metadata_callback_(const FLAC__FileDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
84 static void error_callback_(const FLAC__FileDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
85
86 InputPlugin flac_ip =
87 {
88         NULL,
89         NULL,
90         "Reference FLAC Player v" VERSION,
91         FLAC_XMMS__init,
92         FLAC_XMMS__aboutbox,
93         FLAC_XMMS__configure,
94         FLAC_XMMS__is_our_file,
95         NULL,
96         FLAC_XMMS__play_file,
97         FLAC_XMMS__stop,
98         FLAC_XMMS__pause,
99         FLAC_XMMS__seek,
100         NULL,
101         FLAC_XMMS__get_time,
102         NULL,
103         NULL,
104         FLAC_XMMS__cleanup,
105         NULL,
106         NULL,
107         NULL,
108         NULL,
109         FLAC_XMMS__get_song_info,
110         NULL,           /* file_info_box */
111         NULL
112 };
113
114 #define SAMPLES_PER_WRITE 512
115 static FLAC__int32 reservoir_[FLAC__MAX_BLOCK_SIZE * 2/*for overflow*/ * FLAC_PLUGIN__MAX_SUPPORTED_CHANNELS];
116 static FLAC__byte sample_buffer_[SAMPLES_PER_WRITE * FLAC_PLUGIN__MAX_SUPPORTED_CHANNELS * (24/8)]; /* (24/8) for max bytes per sample */
117 static unsigned wide_samples_in_reservoir_ = 0;
118 static FLAC__FileDecoder *decoder_ = 0;
119 static file_info_struct file_info_;
120 static pthread_t decode_thread_;
121 static FLAC__bool audio_error_ = false;
122
123 InputPlugin *get_iplugin_info()
124 {
125         flac_ip.description = g_strdup_printf("Reference FLAC Player v%s", FLAC__VERSION_STRING);
126         return &flac_ip;
127 }
128
129 void FLAC_XMMS__init()
130 {
131         ConfigFile *cfg;
132
133         flac_cfg.title.tag_override = FALSE;
134         g_free(flac_cfg.title.tag_format);
135         flac_cfg.title.convert_char_set = FALSE;
136
137         cfg = xmms_cfg_open_default_file();
138
139         /* title */
140
141         xmms_cfg_read_boolean(cfg, "flac", "title.tag_override", &flac_cfg.title.tag_override);
142
143         if(!xmms_cfg_read_string(cfg, "flac", "title.tag_format", &flac_cfg.title.tag_format))
144                 flac_cfg.title.tag_format = g_strdup("%p - %t");
145
146         xmms_cfg_read_boolean(cfg, "flac", "title.convert_char_set", &flac_cfg.title.convert_char_set);
147
148         if(!xmms_cfg_read_string(cfg, "flac", "title.file_char_set", &flac_cfg.title.file_char_set))
149                 flac_cfg.title.file_char_set = FLAC_plugin__charset_get_current();
150
151         if(!xmms_cfg_read_string(cfg, "flac", "title.user_char_set", &flac_cfg.title.user_char_set))
152                 flac_cfg.title.user_char_set = FLAC_plugin__charset_get_current();
153
154         /* replaygain */
155
156         xmms_cfg_read_boolean(cfg, "flac", "output.replaygain.enable", &flac_cfg.output.replaygain.enable);
157
158         xmms_cfg_read_boolean(cfg, "flac", "output.replaygain.album_mode", &flac_cfg.output.replaygain.album_mode);
159
160         if(!xmms_cfg_read_int(cfg, "flac", "output.replaygain.preamp", &flac_cfg.output.replaygain.preamp))
161                 flac_cfg.output.replaygain.preamp = 0;
162
163         xmms_cfg_read_boolean(cfg, "flac", "output.replaygain.hard_limit", &flac_cfg.output.replaygain.hard_limit);
164
165         xmms_cfg_read_boolean(cfg, "flac", "output.resolution.normal.dither_24_to_16", &flac_cfg.output.resolution.normal.dither_24_to_16);
166         xmms_cfg_read_boolean(cfg, "flac", "output.resolution.replaygain.dither", &flac_cfg.output.resolution.replaygain.dither);
167
168         if(!xmms_cfg_read_int(cfg, "flac", "output.resolution.replaygain.noise_shaping", &flac_cfg.output.resolution.replaygain.noise_shaping))
169                 flac_cfg.output.resolution.replaygain.noise_shaping = 1;
170
171         if(!xmms_cfg_read_int(cfg, "flac", "output.resolution.replaygain.bps_out", &flac_cfg.output.resolution.replaygain.bps_out))
172                 flac_cfg.output.resolution.replaygain.bps_out = 16;
173
174         decoder_ = FLAC__file_decoder_new();
175 }
176
177 int FLAC_XMMS__is_our_file(char *filename)
178 {
179         char *ext;
180
181         ext = strrchr(filename, '.');
182         if(ext)
183                 if(!strcasecmp(ext, ".flac") || !strcasecmp(ext, ".fla"))
184                         return 1;
185         return 0;
186 }
187
188 void FLAC_XMMS__play_file(char *filename)
189 {
190         FILE *f;
191         gchar *ret;
192
193         wide_samples_in_reservoir_ = 0;
194         audio_error_ = false;
195         file_info_.abort_flag = false;
196         file_info_.is_playing = false;
197         file_info_.eof = false;
198         file_info_.play_thread_open = false;
199         file_info_.has_replaygain = false;
200
201         if(0 == (f = fopen(filename, "r")))
202                 return;
203         fclose(f);
204
205         if(decoder_ == 0)
206                 return;
207
208         if(!safe_decoder_init_(filename, decoder_))
209                 return;
210
211         if(file_info_.has_replaygain && flac_cfg.output.replaygain.enable && flac_cfg.output.resolution.replaygain.dither)
212                 FLAC__plugin_common__init_dither_context(&file_info_.dither_context, file_info_.bits_per_sample, flac_cfg.output.resolution.replaygain.noise_shaping);
213
214         file_info_.is_playing = true;
215
216         if(flac_ip.output->open_audio(file_info_.sample_format, file_info_.sample_rate, file_info_.channels) == 0) {
217                 audio_error_ = true;
218                 safe_decoder_finish_(decoder_);
219                 return;
220         }
221
222         ret = flac_format_song_title(filename);
223         flac_ip.set_info(ret, file_info_.length_in_msec, file_info_.sample_rate * file_info_.channels * file_info_.bits_per_sample, file_info_.sample_rate, file_info_.channels);
224
225         g_free(ret);
226
227         file_info_.seek_to_in_sec = -1;
228         file_info_.play_thread_open = true;
229         pthread_create(&decode_thread_, NULL, play_loop_, NULL);
230 }
231
232 void FLAC_XMMS__stop()
233 {
234         if(file_info_.is_playing) {
235                 file_info_.is_playing = false;
236                 if(file_info_.play_thread_open) {
237                         file_info_.play_thread_open = false;
238                         pthread_join(decode_thread_, NULL);
239                 }
240                 flac_ip.output->close_audio();
241                 safe_decoder_finish_(decoder_);
242         }
243 }
244
245 void FLAC_XMMS__pause(short p)
246 {
247         flac_ip.output->pause(p);
248 }
249
250 void FLAC_XMMS__seek(int time)
251 {
252         file_info_.seek_to_in_sec = time;
253         file_info_.eof = false;
254
255         while(file_info_.seek_to_in_sec != -1)
256                 xmms_usleep(10000);
257 }
258
259 int FLAC_XMMS__get_time()
260 {
261         if(audio_error_)
262                 return -2;
263         if(!file_info_.is_playing || (file_info_.eof && !flac_ip.output->buffer_playing()))
264                 return -1;
265         else
266                 return flac_ip.output->output_time();
267 }
268
269 void FLAC_XMMS__cleanup()
270 {
271         safe_decoder_delete_(decoder_);
272         decoder_ = 0;
273 }
274
275 void FLAC_XMMS__get_song_info(char *filename, char **title, int *length_in_msec)
276 {
277         FLAC__StreamMetadata streaminfo;
278
279         if(0 == filename)
280                 filename = "";
281
282         if(!FLAC__metadata_get_streaminfo(filename, &streaminfo)) {
283                 /* @@@ how to report the error? */
284                 if(title) {
285                         static const char *errtitle = "Invalid FLAC File: ";
286                         *title = g_malloc(strlen(errtitle) + 1 + strlen(filename) + 1 + 1);
287                         sprintf(*title, "%s\"%s\"", errtitle, filename);
288                 }
289                 if(length_in_msec)
290                         *length_in_msec = -1;
291                 return;
292         }
293
294         if(title) {
295                 *title = flac_format_song_title(filename);
296         }
297         if(length_in_msec)
298                 *length_in_msec = streaminfo.data.stream_info.total_samples * 10 / (streaminfo.data.stream_info.sample_rate / 100);
299 }
300
301 /***********************************************************************
302  * local routines
303  **********************************************************************/
304
305 void *play_loop_(void *arg)
306 {
307         (void)arg;
308
309         while(file_info_.is_playing) {
310                 if(!file_info_.eof) {
311                         while(wide_samples_in_reservoir_ < SAMPLES_PER_WRITE) {
312                                 if(FLAC__file_decoder_get_state(decoder_) == FLAC__FILE_DECODER_END_OF_FILE) {
313                                         file_info_.eof = true;
314                                         break;
315                                 }
316                                 else if(!FLAC__file_decoder_process_single(decoder_)) {
317                                         /*@@@ this should probably be a dialog */
318                                         fprintf(stderr, "libxmms-flac: READ ERROR processing frame\n");
319                                         file_info_.eof = true;
320                                         break;
321                                 }
322                         }
323                         if(wide_samples_in_reservoir_ > 0) {
324                                 const unsigned channels = file_info_.channels;
325                                 const unsigned bits_per_sample = file_info_.bits_per_sample;
326                                 const unsigned n = min(wide_samples_in_reservoir_, SAMPLES_PER_WRITE);
327                                 const unsigned delta = n * channels;
328                                 int bytes;
329                                 unsigned i;
330
331                                 if(flac_cfg.output.replaygain.enable && file_info_.has_replaygain) {
332                                         bytes = (int)FLAC__plugin_common__apply_gain(
333                                                 sample_buffer_,
334                                                 reservoir_,
335                                                 n,
336                                                 channels,
337                                                 bits_per_sample,
338                                                 flac_cfg.output.resolution.replaygain.bps_out,
339                                                 file_info_.replay_scale,
340                                                 flac_cfg.output.replaygain.hard_limit,
341                                                 flac_cfg.output.resolution.replaygain.dither,
342                                                 (NoiseShaping)flac_cfg.output.resolution.replaygain.noise_shaping,
343                                                 &file_info_.dither_context
344                                         );
345                                 }
346                                 else {
347                                         bytes = (int)FLAC__plugin_common__pack_pcm_signed_little_endian(
348                                                 sample_buffer_,
349                                                 reservoir_,
350                                                 n,
351                                                 channels,
352                                                 bits_per_sample,
353                                                 flac_cfg.output.resolution.normal.dither_24_to_16?
354                                                         min(bits_per_sample, 16) :
355                                                         bits_per_sample
356                                         );
357                                 }
358
359                                 for(i = delta; i < wide_samples_in_reservoir_ * channels; i++)
360                                         reservoir_[i-delta] = reservoir_[i];
361                                 wide_samples_in_reservoir_ -= n;
362
363                                 flac_ip.add_vis_pcm(flac_ip.output->written_time(), file_info_.sample_format, channels, bytes, sample_buffer_);
364                                 while(flac_ip.output->buffer_free() < (int)bytes && file_info_.is_playing && file_info_.seek_to_in_sec == -1)
365                                         xmms_usleep(10000);
366                                 if(file_info_.is_playing && file_info_.seek_to_in_sec == -1)
367                                         flac_ip.output->write_audio(sample_buffer_, bytes);
368                         }
369                         else {
370                                 file_info_.eof = true;
371                                 xmms_usleep(10000);
372                         }
373                 }
374                 else
375                         xmms_usleep(10000);
376                 if(file_info_.seek_to_in_sec != -1) {
377                         const double distance = (double)file_info_.seek_to_in_sec * 1000.0 / (double)file_info_.length_in_msec;
378                         unsigned target_sample = (unsigned)(distance * (double)file_info_.total_samples);
379                         if(FLAC__file_decoder_seek_absolute(decoder_, (FLAC__uint64)target_sample)) {
380                                 flac_ip.output->flush(file_info_.seek_to_in_sec * 1000);
381                                 file_info_.seek_to_in_sec = -1;
382                                 file_info_.eof = false;
383                                 wide_samples_in_reservoir_ = 0;
384                         }
385                 }
386         }
387
388         safe_decoder_finish_(decoder_);
389
390         /* are these two calls necessary? */
391         flac_ip.output->buffer_free();
392         flac_ip.output->buffer_free();
393
394         pthread_exit(NULL);
395         return 0; /* to silence the compiler warning about not returning a value */
396 }
397
398 FLAC__bool safe_decoder_init_(const char *filename, FLAC__FileDecoder *decoder)
399 {
400         if(decoder == 0)
401                 return false;
402
403         safe_decoder_finish_(decoder);
404
405         FLAC__file_decoder_set_md5_checking(decoder, false);
406         FLAC__file_decoder_set_filename(decoder, filename);
407         FLAC__file_decoder_set_metadata_ignore_all(decoder);
408         FLAC__file_decoder_set_metadata_respond(decoder, FLAC__METADATA_TYPE_STREAMINFO);
409         FLAC__file_decoder_set_metadata_respond(decoder, FLAC__METADATA_TYPE_VORBIS_COMMENT);
410         FLAC__file_decoder_set_write_callback(decoder, write_callback_);
411         FLAC__file_decoder_set_metadata_callback(decoder, metadata_callback_);
412         FLAC__file_decoder_set_error_callback(decoder, error_callback_);
413         FLAC__file_decoder_set_client_data(decoder, &file_info_);
414         if(FLAC__file_decoder_init(decoder) != FLAC__FILE_DECODER_OK)
415                 return false;
416
417         if(!FLAC__file_decoder_process_until_end_of_metadata(decoder))
418                 return false;
419
420         return true;
421 }
422
423 void safe_decoder_finish_(FLAC__FileDecoder *decoder)
424 {
425         if(decoder && FLAC__file_decoder_get_state(decoder) != FLAC__FILE_DECODER_UNINITIALIZED)
426                 FLAC__file_decoder_finish(decoder);
427 }
428
429 void safe_decoder_delete_(FLAC__FileDecoder *decoder)
430 {
431         if(decoder) {
432                 safe_decoder_finish_(decoder);
433                 FLAC__file_decoder_delete(decoder);
434         }
435 }
436
437 FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__FileDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
438 {
439         file_info_struct *file_info = (file_info_struct *)client_data;
440         const unsigned channels = file_info->channels, wide_samples = frame->header.blocksize;
441         unsigned wide_sample, offset_sample, channel;
442
443         (void)decoder;
444
445         if(file_info->abort_flag)
446                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
447
448         for(offset_sample = wide_samples_in_reservoir_ * channels, wide_sample = 0; wide_sample < wide_samples; wide_sample++)
449                 for(channel = 0; channel < channels; channel++, offset_sample++)
450                         reservoir_[offset_sample] = buffer[channel][wide_sample];
451
452         wide_samples_in_reservoir_ += wide_samples;
453
454         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
455 }
456
457 void metadata_callback_(const FLAC__FileDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
458 {
459         file_info_struct *file_info = (file_info_struct *)client_data;
460         (void)decoder;
461         if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
462                 FLAC__ASSERT(metadata->data.stream_info.total_samples < 0x100000000); /* this plugin can only handle < 4 gigasamples */
463                 file_info->total_samples = (unsigned)(metadata->data.stream_info.total_samples&0xffffffff);
464                 file_info->bits_per_sample = metadata->data.stream_info.bits_per_sample;
465                 file_info->channels = metadata->data.stream_info.channels;
466                 file_info->sample_rate = metadata->data.stream_info.sample_rate;
467
468 #ifdef FLAC__DO_DITHER
469                 if(file_info->bits_per_sample == 8) {
470                         file_info->sample_format = FMT_S8;
471                 }
472                 else if(file_info->bits_per_sample == 16 || file_info->bits_per_sample == 24) {
473                         file_info->sample_format = FMT_S16_LE;
474                 }
475                 else {
476                         /*@@@ need some error here like wa2: MessageBox(mod_.hMainWindow, "ERROR: plugin can only handle 8/16/24-bit samples\n", "ERROR: plugin can only handle 8/16/24-bit samples", 0); */
477                         file_info->abort_flag = true;
478                         return;
479                 }
480 #else
481                 if(file_info->bits_per_sample == 8) {
482                         file_info->sample_format = FMT_S8;
483                 }
484                 else if(file_info->bits_per_sample == 16) {
485                         file_info->sample_format = FMT_S16_LE;
486                 }
487                 else {
488                         /*@@@ 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); */
489                         file_info->abort_flag = true;
490                         return;
491                 }
492 #endif
493                 file_info->length_in_msec = file_info->total_samples * 10 / (file_info->sample_rate / 100);
494         }
495         else if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
496                 double gain, peak;
497                 if(FLAC__replaygain_load_from_vorbiscomment(metadata, flac_cfg.output.replaygain.album_mode, &gain, &peak)) {
498                         file_info_.has_replaygain = true;
499                         file_info_.replay_scale = FLAC__replaygain_compute_scale_factor(peak, gain, (double)flac_cfg.output.replaygain.preamp, /*prevent_clipping=*/true);
500                 }
501         }
502 }
503
504 void error_callback_(const FLAC__FileDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
505 {
506         file_info_struct *file_info = (file_info_struct *)client_data;
507         (void)decoder;
508         if(status != FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC)
509                 file_info->abort_flag = true;
510 }