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