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