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