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