make RESERVOIR_TEST the default, remove old code
[flac.git] / src / plugin_xmms / plugin.c
1 /* libxmms-flac - XMMS FLAC input plugin
2  * Copyright (C) 2000,2001  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 <assert.h>
24 #include <glib.h>
25
26 #include "xmms/plugin.h"
27 #include "xmms/util.h"
28 #include "FLAC/all.h"
29
30 #ifdef min
31 #undef min
32 #endif
33 #define min(x,y) ((x)<(y)?(x):(y))
34
35 typedef struct {
36         byte raw[128];
37         char title[31];
38         char artist[31];
39         char album[31];
40         char comment[31];
41         unsigned year;
42         unsigned track; /* may be 0 if v1 (not v1.1) tag */
43         unsigned genre;
44         char description[1024]; /* the formatted description passed to xmms */
45 } id3v1_struct;
46
47 typedef struct {
48         bool abort_flag;
49         bool is_playing;
50         bool eof;
51         unsigned total_samples;
52         unsigned bits_per_sample;
53         unsigned channels;
54         unsigned sample_rate;
55         unsigned length_in_msec;
56         AFormat sample_format;
57         int seek_to_in_sec;
58 } file_info_struct;
59
60 static void FLAC_XMMS__init();
61 static int  FLAC_XMMS__is_our_file(char *filename);
62 static void FLAC_XMMS__play_file(char *filename);
63 static void FLAC_XMMS__stop();
64 static void FLAC_XMMS__pause(short p);
65 static void FLAC_XMMS__seek(int time);
66 static int  FLAC_XMMS__get_time();
67 static void FLAC_XMMS__cleanup();
68 static void FLAC_XMMS__get_song_info(char *filename, char **title, int *length);
69
70 static bool get_id3v1_tag_(const char *filename, id3v1_struct *tag);
71 static void *play_loop_(void *arg);
72 static bool decoder_init_(const char *filename);
73 static FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__FileDecoder *decoder, const FLAC__Frame *frame, const int32 *buffer[], void *client_data);
74 static void metadata_callback_(const FLAC__FileDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data);
75 static void error_callback_(const FLAC__FileDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
76
77
78 InputPlugin flac_ip =
79 {
80         NULL,
81         NULL,
82         "FLAC Player v" FLAC__VERSION_STRING,
83         FLAC_XMMS__init,
84         NULL,
85         NULL,
86         FLAC_XMMS__is_our_file,
87         NULL,
88         FLAC_XMMS__play_file,
89         FLAC_XMMS__stop,
90         FLAC_XMMS__pause,
91         FLAC_XMMS__seek,
92         NULL,
93         FLAC_XMMS__get_time,
94         NULL,
95         NULL,
96         FLAC_XMMS__cleanup,
97         NULL,
98         NULL,
99         NULL,
100         NULL,
101         FLAC_XMMS__get_song_info,
102         NULL,                   /* file_info_box */
103         NULL
104 };
105
106 #define SAMPLES_PER_WRITE 512
107 static byte reservoir_[FLAC__MAX_BLOCK_SIZE * 2 * 2 * 2]; /* *2 for max bytes-per-sample, *2 for max channels, another *2 for overflow */
108 static byte output_[FLAC__MAX_BLOCK_SIZE * 2 * 2]; /* *2 for max bytes-per-sample, *2 for max channels */
109 static unsigned reservoir_samples_;
110 static FLAC__FileDecoder *decoder_;
111 static file_info_struct file_info_;
112 static pthread_t decode_thread_;
113 static bool audio_error_ = false;
114
115 InputPlugin *get_iplugin_info()
116 {
117         flac_ip.description = g_strdup_printf("FLAC Player v%s", FLAC__VERSION_STRING);
118         return &flac_ip;
119 }
120
121 void FLAC_XMMS__init()
122 {
123         decoder_ = FLAC__file_decoder_get_new_instance();
124 }
125
126 int FLAC_XMMS__is_our_file(char *filename)
127 {
128         char *ext;
129
130         ext = strrchr(filename, '.');
131         if (ext)
132                 if (!strcasecmp(ext, ".flac") || !strcasecmp(ext, ".fla"))
133                         return 1;
134         return 0;
135 }
136
137 void FLAC_XMMS__play_file(char *filename)
138 {
139         FILE *f;
140         id3v1_struct tag;
141
142         if(0 == (f = fopen(filename, "r")))
143                 return;
144         fclose(f);
145
146         if(!decoder_init_(filename))
147                 return;
148
149         reservoir_samples_ = 0;
150         audio_error_ = false;
151         file_info_.is_playing = true;
152         file_info_.eof = false;
153
154         if (flac_ip.output->open_audio(file_info_.sample_format, file_info_.sample_rate, file_info_.channels) == 0) {
155                 audio_error_ = true;
156                 if(decoder_ && decoder_->state != FLAC__FILE_DECODER_UNINITIALIZED)
157                         FLAC__file_decoder_finish(decoder_);
158                 return;
159         }
160
161         (void)get_id3v1_tag_(filename, &tag);
162         flac_ip.set_info(tag.description, file_info_.length_in_msec, file_info_.sample_rate * file_info_.channels * file_info_.bits_per_sample, file_info_.sample_rate, file_info_.channels);
163
164         file_info_.seek_to_in_sec = -1;
165         pthread_create(&decode_thread_, NULL, play_loop_, NULL);
166 }
167
168 void FLAC_XMMS__stop()
169 {
170         if(file_info_.is_playing) {
171                 file_info_.is_playing = false;
172                 pthread_join(decode_thread_, NULL);
173                 flac_ip.output->close_audio();
174                 if(decoder_ && decoder_->state != FLAC__FILE_DECODER_UNINITIALIZED)
175                         FLAC__file_decoder_finish(decoder_);
176         }
177 }
178
179 void FLAC_XMMS__pause(short p)
180 {
181         flac_ip.output->pause(p);
182 }
183
184 void FLAC_XMMS__seek(int time)
185 {
186         file_info_.seek_to_in_sec = time;
187         file_info_.eof = false;
188
189         while(file_info_.seek_to_in_sec != -1)
190                 xmms_usleep(10000);
191 }
192
193 int FLAC_XMMS__get_time()
194 {
195         if(audio_error_)
196                 return -2;
197         if(!file_info_.is_playing || (file_info_.eof && !flac_ip.output->buffer_playing()))
198                 return -1;
199         else
200                 return flac_ip.output->output_time();
201 }
202
203 void FLAC_XMMS__cleanup()
204 {
205         if(decoder_)
206                 FLAC__file_decoder_free_instance(decoder_);
207 }
208
209 void FLAC_XMMS__get_song_info(char *filename, char **title, int *length_in_msec)
210 {
211         id3v1_struct tag;
212
213         if(title) {
214                 (void)get_id3v1_tag_(filename, &tag);
215                 *title = g_malloc(strlen(tag.description)+1);
216                 strcpy(*title, tag.description);
217         }
218         if(length_in_msec) {
219                 FLAC__FileDecoder *tmp_decoder = FLAC__file_decoder_get_new_instance();
220                 file_info_struct tmp_file_info;
221                 if(0 == tmp_decoder) {
222                         *length_in_msec = -1;
223                         return;
224                 }
225                 tmp_file_info.abort_flag = false;
226                 tmp_decoder->check_md5 = false; /* turn off MD5 checking in the decoder */
227                 if(FLAC__file_decoder_init(tmp_decoder, filename, write_callback_, metadata_callback_, error_callback_, &tmp_file_info) != FLAC__FILE_DECODER_OK) {
228                         *length_in_msec = -1;
229                         return;
230                 }
231                 if(!FLAC__file_decoder_process_metadata(tmp_decoder)) {
232                         *length_in_msec = -1;
233                         return;
234                 }
235
236                 *length_in_msec = (int)tmp_file_info.length_in_msec;
237
238                 if(tmp_decoder->state != FLAC__FILE_DECODER_UNINITIALIZED)
239                         FLAC__file_decoder_finish(tmp_decoder);
240                 FLAC__file_decoder_free_instance(tmp_decoder);
241         }
242 }
243
244 /***********************************************************************
245  * local routines
246  **********************************************************************/
247
248 bool get_id3v1_tag_(const char *filename, id3v1_struct *tag)
249 {
250         const char *temp;
251         FILE *f = fopen(filename, "rb");
252         memset(tag, 0, sizeof(id3v1_struct));
253
254         /* set the title and description to the filename by default */
255         temp = strrchr(filename, '/');
256         if(!temp)
257                 temp = filename;
258         else
259                 temp++;
260         strcpy(tag->description, temp);
261         *strrchr(tag->description, '.') = '\0';
262         strncpy(tag->title, tag->description, 30); tag->title[30] = '\0';
263
264         if(0 == f)
265                 return false;
266         if(-1 == fseek(f, -128, SEEK_END)) {
267                 fclose(f);
268                 return false;
269         }
270         if(fread(tag->raw, 1, 128, f) < 128) {
271                 fclose(f);
272                 return false;
273         }
274         fclose(f);
275         if(strncmp(tag->raw, "TAG", 3))
276                 return false;
277         else {
278                 char year_str[5];
279
280                 memcpy(tag->title, tag->raw+3, 30);
281                 memcpy(tag->artist, tag->raw+33, 30);
282                 memcpy(tag->album, tag->raw+63, 30);
283                 memcpy(year_str, tag->raw+93, 4); year_str[4] = '\0'; tag->year = atoi(year_str);
284                 memcpy(tag->comment, tag->raw+97, 30);
285                 tag->genre = (unsigned)((byte)tag->raw[127]);
286                 tag->track = (unsigned)((byte)tag->raw[126]);
287
288                 sprintf(tag->description, "%s - %s", tag->artist, tag->title);
289
290                 return true;
291         }
292 }
293
294 void *play_loop_(void *arg)
295 {
296
297         (void)arg;
298
299         while(file_info_.is_playing) {
300                 if(!file_info_.eof) {
301                         while(reservoir_samples_ < SAMPLES_PER_WRITE) {
302                                 if(decoder_->state == FLAC__FILE_DECODER_END_OF_FILE) {
303                                         file_info_.eof = true;
304                                         break;
305                                 }
306                                 else if(!FLAC__file_decoder_process_one_frame(decoder_))
307                                         break;
308                         }
309                         if(reservoir_samples_ > 0) {
310                                 const unsigned channels = file_info_.channels;
311                                 const unsigned bytes_per_sample = (file_info_.bits_per_sample+7)/8;
312                                 unsigned i, n = min(reservoir_samples_, SAMPLES_PER_WRITE), delta;
313                                 unsigned bytes = n * bytes_per_sample * channels;
314
315                                 for(i = 0; i < bytes; i++)
316                                         output_[i] = reservoir_[i];
317                                 delta = i;
318                                 for( ; i < reservoir_samples_*bytes_per_sample*channels; i++)
319                                         reservoir_[i-delta] = reservoir_[i];
320                                 reservoir_samples_ -= n;
321
322                                 flac_ip.add_vis_pcm(flac_ip.output->written_time(), file_info_.sample_format, channels, bytes, output_);
323                                 while(flac_ip.output->buffer_free() < (int)bytes && file_info_.is_playing && file_info_.seek_to_in_sec == -1)
324                                         xmms_usleep(10000);
325                                 if(file_info_.is_playing && file_info_.seek_to_in_sec == -1)
326                                         flac_ip.output->write_audio(output_, bytes);
327                         }
328                         else {
329                                 file_info_.eof = true;
330                                 xmms_usleep(10000);
331                         }
332                 }
333                 else
334                         xmms_usleep(10000);
335                 if (file_info_.seek_to_in_sec != -1) {
336                         const double distance = (double)file_info_.seek_to_in_sec * 1000.0 / (double)file_info_.length_in_msec;
337                         unsigned target_sample = (unsigned)(distance * (double)file_info_.total_samples);
338                         if(FLAC__file_decoder_seek_absolute(decoder_, (uint64)target_sample)) {
339                                 flac_ip.output->flush(file_info_.seek_to_in_sec * 1000);
340                                 file_info_.seek_to_in_sec = -1;
341                                 file_info_.eof = false;
342                                 reservoir_samples_ = 0;
343                         }
344                 }
345
346         }
347         if(decoder_ && decoder_->state != FLAC__FILE_DECODER_UNINITIALIZED)
348                 FLAC__file_decoder_finish(decoder_);
349
350         /* are these two calls necessary? */
351         flac_ip.output->buffer_free();
352         flac_ip.output->buffer_free();
353
354         pthread_exit(NULL);
355         return 0; /* to silence the compiler warning about not returning a value */
356 }
357
358 bool decoder_init_(const char *filename)
359 {
360         if(decoder_ == 0)
361                 return false;
362
363         decoder_->check_md5 = false; /* turn off MD5 checking in the decoder */
364
365         if(FLAC__file_decoder_init(decoder_, filename, write_callback_, metadata_callback_, error_callback_, &file_info_) != FLAC__FILE_DECODER_OK)
366                 return false;
367
368         file_info_.abort_flag = false;
369
370         if(!FLAC__file_decoder_process_metadata(decoder_))
371                 return false;
372
373         return true;
374 }
375
376 FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__FileDecoder *decoder, const FLAC__Frame *frame, const int32 *buffer[], void *client_data)
377 {
378         file_info_struct *file_info = (file_info_struct *)client_data;
379         const unsigned bps = file_info->bits_per_sample, channels = file_info->channels, wide_samples = frame->header.blocksize;
380         unsigned wide_sample, sample, channel;
381         int8 *scbuffer = (int8*)reservoir_;
382         int16 *ssbuffer = (int16*)reservoir_;
383
384         (void)decoder;
385
386         if(file_info->abort_flag)
387                 return FLAC__STREAM_DECODER_WRITE_ABORT;
388
389         if(bps == 8) {
390                 for(sample = reservoir_samples_*channels, wide_sample = 0; wide_sample < wide_samples; wide_sample++)
391                         for(channel = 0; channel < channels; channel++, sample++)
392                                 scbuffer[sample] = (int8)buffer[channel][wide_sample];
393         }
394         else if(bps == 16) {
395                 for(sample = reservoir_samples_*channels, wide_sample = 0; wide_sample < wide_samples; wide_sample++)
396                         for(channel = 0; channel < channels; channel++, sample++)
397                                 ssbuffer[sample] = (int16)buffer[channel][wide_sample];
398         }
399         else {
400                 file_info->abort_flag = true;
401                 return FLAC__STREAM_DECODER_WRITE_ABORT;
402         }
403
404         reservoir_samples_ += wide_samples;
405
406         return FLAC__STREAM_DECODER_WRITE_CONTINUE;
407 }
408
409 void metadata_callback_(const FLAC__FileDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data)
410 {
411         file_info_struct *file_info = (file_info_struct *)client_data;
412         (void)decoder;
413         if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
414                 assert(metadata->data.stream_info.total_samples < 0x100000000); /* this plugin can only handle < 4 gigasamples */
415                 file_info->total_samples = (unsigned)(metadata->data.stream_info.total_samples&0xffffffff);
416                 file_info->bits_per_sample = metadata->data.stream_info.bits_per_sample;
417                 file_info->channels = metadata->data.stream_info.channels;
418                 file_info->sample_rate = metadata->data.stream_info.sample_rate;
419
420                 if(file_info->bits_per_sample == 8) {
421                         file_info->sample_format = FMT_S8;
422                 }
423                 else if(file_info->bits_per_sample == 16) {
424                         file_info->sample_format = FMT_S16_NE;
425                 }
426                 else {
427                         file_info->abort_flag = true;
428                         return;
429                 }
430                 file_info->length_in_msec = file_info->total_samples * 10 / (file_info->sample_rate / 100);
431         }
432 }
433
434 void error_callback_(const FLAC__FileDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
435 {
436         file_info_struct *file_info = (file_info_struct *)client_data;
437         (void)decoder;
438         if(status != FLAC__STREAM_DECODER_ERROR_LOST_SYNC)
439                 file_info->abort_flag = true;
440 }