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