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