simplify decoder finishing; make thread synchronization more safe
[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 <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 decoder_init_(const char *filename);
73 static FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__FileDecoder *decoder, const FLAC__Frame *frame, const FLAC__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 FLAC__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 FLAC__byte output_[FLAC__MAX_BLOCK_SIZE * 2 * 2]; /* *2 for max bytes-per-sample, *2 for max channels */
109 static unsigned reservoir_samples_ = 0;
110 static FLAC__FileDecoder *decoder_ = 0;
111 static file_info_struct file_info_;
112 static pthread_t decode_thread_;
113 static FLAC__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_new();
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         reservoir_samples_ = 0;
143         audio_error_ = false;
144         file_info_.abort_flag = false;
145         file_info_.is_playing = false;
146         file_info_.eof = false;
147         file_info_.play_thread_open = false;
148
149         if(0 == (f = fopen(filename, "r")))
150                 return;
151         fclose(f);
152
153         if(!decoder_init_(filename))
154                 return;
155
156         file_info_.is_playing = true;
157
158         if(flac_ip.output->open_audio(file_info_.sample_format, file_info_.sample_rate, file_info_.channels) == 0) {
159                 audio_error_ = true;
160                 if(decoder_)
161                         FLAC__file_decoder_finish(decoder_);
162                 return;
163         }
164
165         (void)get_id3v1_tag_(filename, &tag);
166         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);
167
168         file_info_.seek_to_in_sec = -1;
169         file_info_.play_thread_open = true;
170         pthread_create(&decode_thread_, NULL, play_loop_, NULL);
171 }
172
173 void FLAC_XMMS__stop()
174 {
175         if(file_info_.is_playing) {
176                 file_info_.is_playing = false;
177                 if(file_info_.play_thread_open) {
178                         file_info_.play_thread_open = false;
179                         pthread_join(decode_thread_, NULL);
180                 }
181                 flac_ip.output->close_audio();
182                 if(decoder_)
183                         FLAC__file_decoder_finish(decoder_);
184         }
185 }
186
187 void FLAC_XMMS__pause(short p)
188 {
189         flac_ip.output->pause(p);
190 }
191
192 void FLAC_XMMS__seek(int time)
193 {
194         file_info_.seek_to_in_sec = time;
195         file_info_.eof = false;
196
197         while(file_info_.seek_to_in_sec != -1)
198                 xmms_usleep(10000);
199 }
200
201 int FLAC_XMMS__get_time()
202 {
203         if(audio_error_)
204                 return -2;
205         if(!file_info_.is_playing || (file_info_.eof && !flac_ip.output->buffer_playing()))
206                 return -1;
207         else
208                 return flac_ip.output->output_time();
209 }
210
211 void FLAC_XMMS__cleanup()
212 {
213         if(decoder_) {
214                 FLAC__file_decoder_delete(decoder_);
215                 decoder_ = 0;
216         }
217 }
218
219 void FLAC_XMMS__get_song_info(char *filename, char **title, int *length_in_msec)
220 {
221         id3v1_struct tag;
222
223         if(title) {
224                 (void)get_id3v1_tag_(filename, &tag);
225                 *title = g_malloc(strlen(tag.description)+1);
226                 strcpy(*title, tag.description);
227         }
228         if(length_in_msec) {
229                 FLAC__FileDecoder *tmp_decoder = FLAC__file_decoder_new();
230                 file_info_struct tmp_file_info;
231                 if(0 == tmp_decoder) {
232                         *length_in_msec = -1;
233                         return;
234                 }
235                 tmp_file_info.abort_flag = false;
236                 FLAC__file_decoder_set_md5_checking(tmp_decoder, false);
237                 FLAC__file_decoder_set_filename(tmp_decoder, filename);
238                 FLAC__file_decoder_set_write_callback(tmp_decoder, write_callback_);
239                 FLAC__file_decoder_set_metadata_callback(tmp_decoder, metadata_callback_);
240                 FLAC__file_decoder_set_error_callback(tmp_decoder, error_callback_);
241                 FLAC__file_decoder_set_client_data(tmp_decoder, &tmp_file_info);
242                 if(FLAC__file_decoder_init(tmp_decoder) != FLAC__FILE_DECODER_OK) {
243                         *length_in_msec = -1;
244                         return;
245                 }
246                 if(!FLAC__file_decoder_process_metadata(tmp_decoder)) {
247                         *length_in_msec = -1;
248                         return;
249                 }
250
251                 *length_in_msec = (int)tmp_file_info.length_in_msec;
252
253                 FLAC__file_decoder_finish(tmp_decoder);
254                 FLAC__file_decoder_delete(tmp_decoder);
255         }
256 }
257
258 /***********************************************************************
259  * local routines
260  **********************************************************************/
261
262 FLAC__bool get_id3v1_tag_(const char *filename, id3v1_struct *tag)
263 {
264         const char *temp;
265         FILE *f = fopen(filename, "rb");
266         memset(tag, 0, sizeof(id3v1_struct));
267
268         /* set the title and description to the filename by default */
269         temp = strrchr(filename, '/');
270         if(!temp)
271                 temp = filename;
272         else
273                 temp++;
274         strcpy(tag->description, temp);
275         *strrchr(tag->description, '.') = '\0';
276         strncpy(tag->title, tag->description, 30); tag->title[30] = '\0';
277
278         if(0 == f)
279                 return false;
280         if(-1 == fseek(f, -128, SEEK_END)) {
281                 fclose(f);
282                 return false;
283         }
284         if(fread(tag->raw, 1, 128, f) < 128) {
285                 fclose(f);
286                 return false;
287         }
288         fclose(f);
289         if(strncmp(tag->raw, "TAG", 3))
290                 return false;
291         else {
292                 char year_str[5];
293
294                 memcpy(tag->title, tag->raw+3, 30);
295                 memcpy(tag->artist, tag->raw+33, 30);
296                 memcpy(tag->album, tag->raw+63, 30);
297                 memcpy(year_str, tag->raw+93, 4); year_str[4] = '\0'; tag->year = atoi(year_str);
298                 memcpy(tag->comment, tag->raw+97, 30);
299                 tag->genre = (unsigned)((FLAC__byte)tag->raw[127]);
300                 tag->track = (unsigned)((FLAC__byte)tag->raw[126]);
301
302                 sprintf(tag->description, "%s - %s", tag->artist, tag->title);
303
304                 return true;
305         }
306 }
307
308 void *play_loop_(void *arg)
309 {
310         (void)arg;
311
312         while(file_info_.is_playing) {
313                 if(!file_info_.eof) {
314                         while(reservoir_samples_ < SAMPLES_PER_WRITE) {
315                                 if(FLAC__file_decoder_get_state(decoder_) == FLAC__FILE_DECODER_END_OF_FILE) {
316                                         file_info_.eof = true;
317                                         break;
318                                 }
319                                 else if(!FLAC__file_decoder_process_one_frame(decoder_))
320                                         break;
321                         }
322                         if(reservoir_samples_ > 0) {
323                                 const unsigned channels = file_info_.channels;
324                                 const unsigned bytes_per_sample = (file_info_.bits_per_sample+7)/8;
325                                 unsigned i, n = min(reservoir_samples_, SAMPLES_PER_WRITE), delta;
326                                 unsigned bytes = n * bytes_per_sample * channels;
327
328                                 for(i = 0; i < bytes; i++)
329                                         output_[i] = reservoir_[i];
330                                 delta = i;
331                                 for( ; i < reservoir_samples_*bytes_per_sample*channels; i++)
332                                         reservoir_[i-delta] = reservoir_[i];
333                                 reservoir_samples_ -= n;
334
335                                 flac_ip.add_vis_pcm(flac_ip.output->written_time(), file_info_.sample_format, channels, bytes, output_);
336                                 while(flac_ip.output->buffer_free() < (int)bytes && file_info_.is_playing && file_info_.seek_to_in_sec == -1)
337                                         xmms_usleep(10000);
338                                 if(file_info_.is_playing && file_info_.seek_to_in_sec == -1)
339                                         flac_ip.output->write_audio(output_, bytes);
340                         }
341                         else {
342                                 file_info_.eof = true;
343                                 xmms_usleep(10000);
344                         }
345                 }
346                 else
347                         xmms_usleep(10000);
348                 if(file_info_.seek_to_in_sec != -1) {
349                         const double distance = (double)file_info_.seek_to_in_sec * 1000.0 / (double)file_info_.length_in_msec;
350                         unsigned target_sample = (unsigned)(distance * (double)file_info_.total_samples);
351                         if(FLAC__file_decoder_seek_absolute(decoder_, (FLAC__uint64)target_sample)) {
352                                 flac_ip.output->flush(file_info_.seek_to_in_sec * 1000);
353                                 file_info_.seek_to_in_sec = -1;
354                                 file_info_.eof = false;
355                                 reservoir_samples_ = 0;
356                         }
357                 }
358         }
359
360         if(decoder_)
361                 FLAC__file_decoder_finish(decoder_);
362
363         /* are these two calls necessary? */
364         flac_ip.output->buffer_free();
365         flac_ip.output->buffer_free();
366
367         pthread_exit(NULL);
368         return 0; /* to silence the compiler warning about not returning a value */
369 }
370
371 FLAC__bool decoder_init_(const char *filename)
372 {
373         if(decoder_ == 0)
374                 return false;
375
376         FLAC__file_decoder_set_md5_checking(decoder_, false);
377         FLAC__file_decoder_set_filename(decoder_, filename);
378         FLAC__file_decoder_set_write_callback(decoder_, write_callback_);
379         FLAC__file_decoder_set_metadata_callback(decoder_, metadata_callback_);
380         FLAC__file_decoder_set_error_callback(decoder_, error_callback_);
381         FLAC__file_decoder_set_client_data(decoder_, &file_info_);
382         if(FLAC__file_decoder_init(decoder_) != FLAC__FILE_DECODER_OK)
383                 return false;
384
385         if(!FLAC__file_decoder_process_metadata(decoder_))
386                 return false;
387
388         return true;
389 }
390
391 FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__FileDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 *buffer[], void *client_data)
392 {
393         file_info_struct *file_info = (file_info_struct *)client_data;
394         const unsigned bps = file_info->bits_per_sample, channels = file_info->channels, wide_samples = frame->header.blocksize;
395         unsigned wide_sample, sample, channel;
396         FLAC__int8 *scbuffer = (FLAC__int8*)reservoir_;
397         FLAC__int16 *ssbuffer = (FLAC__int16*)reservoir_;
398
399         (void)decoder;
400
401         if(file_info->abort_flag)
402                 return FLAC__STREAM_DECODER_WRITE_ABORT;
403
404         if(bps == 8) {
405                 for(sample = reservoir_samples_*channels, wide_sample = 0; wide_sample < wide_samples; wide_sample++)
406                         for(channel = 0; channel < channels; channel++, sample++)
407                                 scbuffer[sample] = (FLAC__int8)buffer[channel][wide_sample];
408         }
409         else if(bps == 16) {
410                 for(sample = reservoir_samples_*channels, wide_sample = 0; wide_sample < wide_samples; wide_sample++)
411                         for(channel = 0; channel < channels; channel++, sample++)
412                                 ssbuffer[sample] = (FLAC__int16)buffer[channel][wide_sample];
413         }
414         else {
415                 file_info->abort_flag = true;
416                 return FLAC__STREAM_DECODER_WRITE_ABORT;
417         }
418
419         reservoir_samples_ += wide_samples;
420
421         return FLAC__STREAM_DECODER_WRITE_CONTINUE;
422 }
423
424 void metadata_callback_(const FLAC__FileDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data)
425 {
426         file_info_struct *file_info = (file_info_struct *)client_data;
427         (void)decoder;
428         if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
429                 FLAC__ASSERT(metadata->data.stream_info.total_samples < 0x100000000); /* this plugin can only handle < 4 gigasamples */
430                 file_info->total_samples = (unsigned)(metadata->data.stream_info.total_samples&0xffffffff);
431                 file_info->bits_per_sample = metadata->data.stream_info.bits_per_sample;
432                 file_info->channels = metadata->data.stream_info.channels;
433                 file_info->sample_rate = metadata->data.stream_info.sample_rate;
434
435                 if(file_info->bits_per_sample == 8) {
436                         file_info->sample_format = FMT_S8;
437                 }
438                 else if(file_info->bits_per_sample == 16) {
439                         file_info->sample_format = FMT_S16_NE;
440                 }
441                 else {
442                         file_info->abort_flag = true;
443                         return;
444                 }
445                 file_info->length_in_msec = file_info->total_samples * 10 / (file_info->sample_rate / 100);
446         }
447 }
448
449 void error_callback_(const FLAC__FileDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
450 {
451         file_info_struct *file_info = (file_info_struct *)client_data;
452         (void)decoder;
453         if(status != FLAC__STREAM_DECODER_ERROR_LOST_SYNC)
454                 file_info->abort_flag = true;
455 }