1 /*
2  * Copyright (C) 2000-2019 the xine project
3  *
4  * This file is part of xine, a free video player.
5  *
6  * xine is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * xine is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
19  */
20 
21 /*
22  * FLAC File Demuxer by Mike Melanson (melanson@pcisys.net)
23  * For more information on the FLAC file format, visit:
24  *   http://flac.sourceforge.net/
25  */
26 
27 #ifdef HAVE_CONFIG_H
28 #include "config.h"
29 #endif
30 
31 #include <stdio.h>
32 #include <fcntl.h>
33 #include <unistd.h>
34 #include <string.h>
35 #include <stdlib.h>
36 #ifdef HAVE_MALLOC_H
37 #include <malloc.h>
38 #endif
39 
40 #define LOG_MODULE "demux_flac"
41 #define LOG_VERBOSE
42 /*
43 #define LOG
44 */
45 
46 #define USE_FRAME_BUF
47 
48 #include <xine/xine_internal.h>
49 #include <xine/xineutils.h>
50 #include <xine/compat.h>
51 #include <xine/demux.h>
52 #include "bswap.h"
53 #include "group_audio.h"
54 
55 #include "id3.h"
56 #include "flacutils.h"
57 
58 typedef struct {
59   demux_plugin_t       demux_plugin;
60 
61   xine_stream_t       *stream;
62   fifo_buffer_t       *audio_fifo;
63   input_plugin_t      *input;
64   int                  status;
65 
66   int                  sample_rate;
67   int                  bits_per_sample;
68   int                  channels;
69   int64_t              total_samples;
70   off_t                data_start;
71   off_t                data_size;
72 
73   flac_seekpoint_t    *seekpoints;
74   int                  seekpoint_count;
75 
76 #ifdef USE_FRAME_BUF
77   uint8_t              frame_head_crc_tab[256];
78   uint8_t              frame_head[16];
79   uint8_t             *frame_buf;
80   uint32_t             frame_buf_used;
81   uint32_t             frame_buf_size;
82   off_t                frame_buf_filepos;
83   struct {
84     off_t              filepos;
85     uint32_t           rate;
86     uint32_t           bits;
87     uint32_t           channels;
88     uint32_t           vbs;
89     uint32_t           hsize;
90     uint32_t           bsize;
91     uint32_t           num;
92     uint32_t           max_size;
93     uint32_t           buf_pos;
94   }                    frame1, frame2;
95   int64_t              last_pts;
96   int                  seek_flag;
97   int                  read_errs;
98 #endif
99 
100   unsigned char        streaminfo[sizeof(xine_waveformatex) + FLAC_STREAMINFO_SIZE];
101 } demux_flac_t;
102 
103 #ifdef USE_FRAME_BUF
104 static const uint32_t flac_sample_rates[16] = {
105       0, 88200, 176400, 192000,
106    8000, 16000,  22050,  24000,
107   32000, 44100,  48000,  96000,
108       1,     2,      3,      0
109 };
110 
111 static const uint32_t flac_blocksizes[16] = {
112          0,      192,      576,   2 * 576,
113    4 * 576,  8 * 576,        1,         2,
114        256,  2 * 256,  4 * 256,   8 * 256,
115   16 * 256, 32 * 256, 64 * 256, 128 * 256
116 };
117 
118 static const uint8_t flac_sample_sizes[8] = {
119    0,  8, 12, 0,
120   16, 20, 24, 0
121 };
122 
123 static const uint8_t flac_channels[16] = {
124   1, /* mono */
125   2, /* stereo */
126   3, /* surround */
127   4, /* quadrophonic */
128   5, /* 5.0 */
129   6, /* 5.1 */
130   7, /* 6.1 */
131   8, /* 7.1 */
132   2, /* left + side */
133   2, /* right + side */
134   2, /* mid + side */
135   0,
136   0,
137   0,
138   0,
139   0
140 };
141 
flac_init_frame_head(demux_flac_t * flac)142 static void flac_init_frame_head (demux_flac_t *flac) {
143   uint32_t i, j, v;
144   for (i = 0; i < 256; i++) {
145     v = i << 24;
146     for (j = 0; j < 8; j++)
147       v = (v << 1) ^ (0x07000000 & (((int32_t)v) >> 31));
148     flac->frame_head_crc_tab[i] = v >> 24;
149   }
150 }
151 
flac_reset_head(demux_flac_t * flac)152 static void flac_reset_head (demux_flac_t *flac) {
153   flac->frame1.buf_pos = 0;
154   flac->frame2.buf_pos = 0;
155   flac->frame1.hsize   = 0;
156   flac->frame2.hsize   = 0;
157   flac->frame_buf_used = 0;
158 }
159 
flac_test_frame_head(demux_flac_t * flac,uint32_t len)160 static uint32_t flac_test_frame_head (demux_flac_t *flac, uint32_t len) {
161   uint8_t *p = flac->frame_head;
162   uint32_t v = 0;
163   while (len--)
164     v = (v >> 8) ^ flac->frame_head_crc_tab[*p++ ^ (v & 0xff)];
165   return v;
166 }
167 
flac_parse_frame_head(demux_flac_t * flac)168 static int flac_parse_frame_head (demux_flac_t *flac) {
169   const uint8_t *p = flac->frame_head;
170   uint32_t v;
171   /* sync word */
172   if (p[0] != 0xff)
173     return 1;
174   if ((p[1] & 0xfe) != 0xf8)
175     return 1;
176   /* reserved */
177   if (flac->frame_head[3] & 1)
178     return 2;
179   /* variable block size */
180   flac->frame2.vbs = flac->frame_head[1] & 0x01;
181   /* channels */
182   v = flac_channels[flac->frame_head[3] >> 4];
183   if (v == 0)
184     return 2;
185   flac->frame2.channels = v;
186   /* bits */
187   v = flac_sample_sizes[(flac->frame_head[3] >> 1) & 7];
188   if (v == 0)
189     return 2;
190   flac->frame2.bits = v;
191   /* frame num (fixed block size) or sample num (utf8) */
192   p += 4;
193   v = _X_BE_32 (p);
194   if ((v & 0x80000000) == 0) {
195     flac->frame2.num = v >> 24;
196     p += 1;
197   } else if ((v & 0xe0c00000) == 0xc0800000) {
198     flac->frame2.num = ((v & 0x1f000000) >> 18)
199                      | ((v & 0x003f0000) >> 16);
200     p += 2;
201   } else if ((v & 0xf0c0c000) == 0xe0808000) {
202     flac->frame2.num = ((v & 0x0f000000) >> 12)
203                      | ((v & 0x003f0000) >> 10)
204                      | ((v & 0x00003f00) >>  8);
205     p += 3;
206   } else if ((v & 0xf8c0c0c0) == 0xf0808080) {
207     flac->frame2.num = ((v & 0x07000000) >>  6)
208                      | ((v & 0x003f0000) >>  4)
209                      | ((v & 0x00003f00) >>  2)
210                      |  (v & 0x0000003f);
211     p += 4;
212   } else if ((v & 0xfcc0c0c0) == 0xf8808080) {
213     flac->frame2.num =  (v & 0x03000000)
214                      | ((v & 0x003f0000) <<  2)
215                      | ((v & 0x00003f00) <<  4)
216                      | ((v & 0x0000003f) <<  6)
217                      |  (p[4] & 0x3f);
218     p += 5;
219   } else if ((v & 0xfec0c0c0) == 0xfc808080) {
220     flac->frame2.num = ((v & 0x01000000) <<  6)
221                      | ((v & 0x003f0000) <<  8)
222                      | ((v & 0x00003f00) << 10)
223                      | ((v & 0x0000003f) << 12)
224                      | ((p[4] & 0x3f)    <<  6)
225                      |  (p[5] & 0x3f);
226     p += 6;
227   } else {
228     return 2;
229   }
230   /* block size */
231   v = flac_blocksizes[flac->frame_head[2] >> 4];
232   if (v < 4) {
233     switch (v) {
234       case 1:
235         v = *p++ + 1;
236         break;
237       case 2:
238         v = _X_BE_16 (p) + 1; p += 2;
239         break;
240       default:
241         return 2;
242     }
243   }
244   flac->frame2.bsize = v;
245   /* sample rate */
246   v = flac_sample_rates[flac->frame_head[2] & 0x0f];
247   if (v < 4) {
248     switch (v) {
249       case 1:
250         v = *p++ * 1000;
251         break;
252       case 2:
253         v = _X_BE_16 (p); p += 2;
254         break;
255       case 3:
256         v = _X_BE_16 (p) * 10; p += 2;
257         break;
258       default:
259         return 2;
260     }
261   }
262   flac->frame2.rate = v;
263   /* crc test */
264   p++;
265   flac->frame2.hsize = p - flac->frame_head;
266   if (flac_test_frame_head (flac, flac->frame2.hsize) != 0)
267     return 2;
268   /* flac shall make things smaller than the uncompressed size. */
269   /* frame head + frame crc + channel heads */
270   v = 18 + flac->frame2.channels * (((flac->frame2.bits + 7) >> 3) + 1);
271   /* uncompressed samples */
272   if (flac->frame2.channels == 2)
273     v += ((2 * flac->frame2.bits + 1) * flac->frame2.bsize + 7) >> 3;
274   else
275     v += (flac->frame2.channels * flac->frame2.bits * flac->frame2.bsize + 7) >> 3;
276   flac->frame2.max_size = v;
277   return 0;
278 }
279 
flac_get_frame(demux_flac_t * flac)280 static int flac_get_frame (demux_flac_t *flac) {
281   int r = -1;
282   uint32_t v;
283   uint8_t *p, *e;
284 
285   flac->frame1 = flac->frame2;
286   p = flac->frame_buf + flac->frame2.buf_pos + flac->frame2.hsize;
287   e = flac->frame_buf + flac->frame_buf_used;
288   memcpy (e, "\xff\xf8\x00\x00", 4);
289   v = _X_BE_32 (p); p += 4;
290 
291   while (1) {
292     uint32_t l;
293     int32_t  s;
294     while ((v & 0xfffe0001) != 0xfff80000)
295       v = (v << 8) | *p++;
296     if (p + sizeof (flac->frame_head) - 4 <= e) {
297       flac->frame2.buf_pos = p - 4 - flac->frame_buf;
298       flac->frame2.filepos = flac->frame_buf_filepos + flac->frame2.buf_pos;
299       memcpy (flac->frame_head, flac->frame_buf + flac->frame2.buf_pos, sizeof (flac->frame_head));
300       r = flac_parse_frame_head (flac);
301       if (r == 0)
302         break;
303       v = (v << 8) | *p++;
304       continue;
305     }
306     if (flac->frame1.bits == 0) {
307       p = flac->frame_buf + 4;
308       flac->frame1.buf_pos = 0;
309       flac->frame_buf_used = 0;
310     } else if (flac->frame1.buf_pos) {
311       l = flac->frame_buf_used - flac->frame1.buf_pos;
312       if (l) {
313         if (l <= flac->frame1.buf_pos)
314           memcpy (flac->frame_buf, flac->frame_buf + flac->frame1.buf_pos, l);
315         else
316           memmove (flac->frame_buf, flac->frame_buf + flac->frame1.buf_pos, l);
317       }
318       p -= flac->frame1.buf_pos;
319       flac->frame1.buf_pos = 0;
320       flac->frame_buf_used = l;
321     }
322     flac->frame2.buf_pos = p - 4 - flac->frame_buf;
323     flac->frame2.hsize = 0;
324     l = flac->frame_buf_size - flac->frame_buf_used;
325     if (!l)
326       break;
327     flac->frame_buf_filepos = flac->input->get_current_pos (flac->input) - flac->frame_buf_used;
328     s = flac->input->read (flac->input, flac->frame_buf + flac->frame_buf_used, l);
329     if (s <= 0)
330       break;
331     flac->frame_buf_used += s;
332     e = flac->frame_buf + flac->frame_buf_used;
333     memcpy (e, "\xff\xf8\x00\x00", 4);
334     v = _X_BE_32 (p - 4);
335   }
336 
337   /* enlarge buf? */
338   if ((r == 0) && (flac->frame2.max_size > flac->frame_buf_size)) {
339     uint32_t need = 3 * flac->frame2.max_size / 2;
340     uint8_t *n = realloc (flac->frame_buf, need + 16);
341     if (n) {
342       flac->frame_buf = n;
343       flac->frame_buf_size = need;
344       xprintf (flac->stream->xine, XINE_VERBOSITY_DEBUG,
345         "demux_flac: frame buffer enlarged to %u bytes.\n", (unsigned int)need);
346     }
347   }
348 
349   return flac->frame2.buf_pos - flac->frame1.buf_pos;
350 }
351 #endif
352 
353 /* Open a flac file
354  * This function is called from the _open() function of this demuxer.
355  * It returns 1 if flac file was opened successfully. */
open_flac_file(demux_flac_t * flac)356 static int open_flac_file(demux_flac_t *flac) {
357 
358   uint32_t signature;
359   unsigned char preamble[10];
360   unsigned int block_length;
361   unsigned char buffer[FLAC_SEEKPOINT_SIZE];
362   unsigned char *streaminfo = flac->streaminfo + sizeof(xine_waveformatex);
363   int i;
364 
365   /* fetch the file signature, 4 bytes will read both the fLaC
366    * signature and the */
367   if (_x_demux_read_header(flac->input, &signature, 4) != 4)
368     return 0;
369 
370   flac->input->seek(flac->input, 4, SEEK_SET);
371 
372   /* Unfortunately some FLAC files have an ID3 flag prefixed on them
373    * before the actual FLAC headers... these are barely legal, but
374    * users use them and want them working, so check and skip the ID3
375    * tag if present.
376    */
377   if ( id3v2_istag(signature) ) {
378     id3v2_parse_tag(flac->input, flac->stream, signature);
379 
380     if ( flac->input->read(flac->input, &signature, 4) != 4 )
381       return 0;
382   }
383 
384   /* validate signature */
385   if ( signature != ME_FOURCC('f', 'L', 'a', 'C') )
386       return 0;
387 
388   /* loop through the metadata blocks; use a do-while construct since there
389    * will always be 1 metadata block */
390   do {
391 
392     if (flac->input->read(flac->input, preamble, FLAC_SIGNATURE_SIZE) !=
393         FLAC_SIGNATURE_SIZE)
394       return 0;
395 
396     block_length = (preamble[1] << 16) |
397                    (preamble[2] <<  8) |
398                    (preamble[3] <<  0);
399 
400     switch (preamble[0] & 0x7F) {
401 
402     /* STREAMINFO */
403     case 0:
404       lprintf ("STREAMINFO metadata\n");
405       if (block_length != FLAC_STREAMINFO_SIZE) {
406         lprintf ("expected STREAMINFO chunk of %d bytes\n",
407           FLAC_STREAMINFO_SIZE);
408         return 0;
409       }
410       if (flac->input->read(flac->input,
411         flac->streaminfo + sizeof(xine_waveformatex),
412         FLAC_STREAMINFO_SIZE) != FLAC_STREAMINFO_SIZE)
413         return 0;
414       flac->sample_rate = _X_BE_32(&streaminfo[10]);
415       flac->channels = ((flac->sample_rate >> 9) & 0x07) + 1;
416       flac->bits_per_sample = ((flac->sample_rate >> 4) & 0x1F) + 1;
417       flac->sample_rate >>= 12;
418       flac->total_samples = _X_BE_64(&streaminfo[10]) & UINT64_C(0x0FFFFFFFFF);  /* 36 bits */
419       lprintf ("%d Hz, %d bits, %d channels, %"PRId64" total samples\n",
420         flac->sample_rate, flac->bits_per_sample,
421         flac->channels, flac->total_samples);
422       break;
423 
424     /* PADDING */
425     case 1:
426       lprintf ("PADDING metadata\n");
427       flac->input->seek(flac->input, block_length, SEEK_CUR);
428       break;
429 
430     /* APPLICATION */
431     case 2:
432       lprintf ("APPLICATION metadata\n");
433       flac->input->seek(flac->input, block_length, SEEK_CUR);
434       break;
435 
436     /* SEEKTABLE */
437     case 3:
438       lprintf ("SEEKTABLE metadata, %d bytes\n", block_length);
439       if (!flac->sample_rate)
440         break;
441       flac->seekpoint_count = block_length / FLAC_SEEKPOINT_SIZE;
442       if (!flac->seekpoint_count)
443         break;
444       flac->seekpoints = calloc(flac->seekpoint_count, sizeof(flac_seekpoint_t));
445       if (!flac->seekpoints)
446         return 0;
447       for (i = 0; i < flac->seekpoint_count; i++) {
448         if (flac->input->read(flac->input, buffer, FLAC_SEEKPOINT_SIZE) != FLAC_SEEKPOINT_SIZE)
449           return 0;
450         flac->seekpoints[i].sample_number = _X_BE_64(&buffer[0]);
451         lprintf (" %d: sample %"PRId64", ", i, flac->seekpoints[i].sample_number);
452         flac->seekpoints[i].offset = _X_BE_64(&buffer[8]);
453         flac->seekpoints[i].size = _X_BE_16(&buffer[16]);
454         lprintf ("@ 0x%"PRIX64", size = %d bytes, ",
455           flac->seekpoints[i].offset, flac->seekpoints[i].size);
456         flac->seekpoints[i].pts = flac->seekpoints[i].sample_number;
457         flac->seekpoints[i].pts *= 90000;
458         flac->seekpoints[i].pts /= flac->sample_rate;
459         lprintf ("pts = %"PRId64"\n", flac->seekpoints[i].pts);
460       }
461       break;
462 
463     /* VORBIS_COMMENT
464      *
465      * For a description of the format please have a look at
466      * http://www.xiph.org/vorbis/doc/v-comment.html */
467     case 4:
468       lprintf ("VORBIS_COMMENT metadata\n");
469       {
470         char *comments;
471         uint32_t length, user_comment_list_length, cn;
472         char *comment;
473         char c;
474 
475         if (block_length < 8)
476           break;
477 
478         comments = malloc(block_length + 1); /* last byte for NUL termination */
479         if (!comments)
480           break;
481 
482         if (flac->input->read(flac->input, comments, block_length) == block_length) {
483           char *ptr = comments;
484           int tracknumber = -1;
485           int tracktotal = -1;
486 
487           length = _X_LE_32(ptr);
488           ptr += 4 + length;
489           if (length > block_length - 8) {
490             free(comments);
491             return 0; /* bad length or too little left in the buffer */
492           }
493 
494           user_comment_list_length = _X_LE_32(ptr);
495           ptr += 4;
496 
497           cn = 0;
498           for (; cn < user_comment_list_length; cn++) {
499             if (ptr > comments + block_length - 4) {
500               free(comments);
501               return 0; /* too little left in the buffer */
502             }
503 
504             length = _X_LE_32(ptr);
505             ptr += 4;
506             if (length >= block_length || ptr + length > comments + block_length) {
507               free(comments);
508               return 0; /* bad length */
509             }
510 
511             comment = (char*) ptr;
512             c = comment[length];
513             comment[length] = 0; /* NUL termination */
514 
515             lprintf ("comment[%02d] = %s\n", cn, comment);
516 
517             if ((strncasecmp ("TITLE=", comment, 6) == 0)
518                 && (length - 6 > 0)) {
519               _x_meta_info_set_utf8 (flac->stream, XINE_META_INFO_TITLE, comment + 6);
520             } else if ((strncasecmp ("ARTIST=", comment, 7) == 0)
521                 && (length - 7 > 0)) {
522               _x_meta_info_set_utf8 (flac->stream, XINE_META_INFO_ARTIST, comment + 7);
523             } else if ((strncasecmp ("COMPOSER=", comment, 9) == 0)
524                 && (length - 9 > 0)) {
525               _x_meta_info_set_utf8 (flac->stream, XINE_META_INFO_COMPOSER, comment + 9);
526             } else if ((strncasecmp ("ALBUM=", comment, 6) == 0)
527                 && (length - 6 > 0)) {
528               _x_meta_info_set_utf8 (flac->stream, XINE_META_INFO_ALBUM, comment + 6);
529             } else if ((strncasecmp ("DATE=", comment, 5) == 0)
530                 && (length - 5 > 0)) {
531               _x_meta_info_set_utf8 (flac->stream, XINE_META_INFO_YEAR, comment + 5);
532             } else if ((strncasecmp ("GENRE=", comment, 6) == 0)
533                 && (length - 6 > 0)) {
534               _x_meta_info_set_utf8 (flac->stream, XINE_META_INFO_GENRE, comment + 6);
535             } else if ((strncasecmp ("Comment=", comment, 8) == 0)
536                 && (length - 8 > 0)) {
537               _x_meta_info_set_utf8 (flac->stream, XINE_META_INFO_COMMENT, comment + 8);
538             } else if ((strncasecmp ("TRACKNUMBER=", comment, 12) == 0)
539                 && (length - 12 > 0)) {
540               tracknumber = atoi (comment + 12);
541             } else if ((strncasecmp ("TRACKTOTAL=", comment, 11) == 0)
542                 && (length - 11 > 0)) {
543               tracktotal = atoi (comment + 11);
544             }
545             comment[length] = c;
546 
547             ptr += length;
548           }
549 
550           if ((tracknumber > 0) && (tracktotal > 0)) {
551             char tn[24];
552             snprintf (tn, 24, "%02d/%02d", tracknumber, tracktotal);
553             _x_meta_info_set(flac->stream, XINE_META_INFO_TRACK_NUMBER, tn);
554           }
555           else if (tracknumber > 0) {
556             char tn[16];
557             snprintf (tn, 16, "%02d", tracknumber);
558             _x_meta_info_set(flac->stream, XINE_META_INFO_TRACK_NUMBER, tn);
559           }
560         }
561         free(comments);
562       }
563       break;
564 
565     /* CUESHEET */
566     case 5:
567       lprintf ("CUESHEET metadata\n");
568       flac->input->seek(flac->input, block_length, SEEK_CUR);
569       break;
570 
571     /* 6-127 are presently reserved */
572     default:
573       lprintf ("unknown metadata chunk: %d\n", preamble[0] & 0x7F);
574       flac->input->seek(flac->input, block_length, SEEK_CUR);
575       break;
576 
577     }
578 
579   } while ((preamble[0] & 0x80) == 0);
580 
581   /* do not bail out yet, maybe decoder can handle this
582   if (!flac->sample_rate)
583     return 0;
584   */
585 
586   flac->data_start = flac->input->get_current_pos(flac->input);
587   flac->data_size = flac->input->get_length(flac->input) - flac->data_start;
588 
589   /* now at the beginning of the audio, adjust the seekpoint offsets */
590   for (i = 0; i < flac->seekpoint_count; i++) {
591     flac->seekpoints[i].offset += flac->data_start;
592   }
593 
594   return 1;
595 }
596 
demux_flac_send_chunk(demux_plugin_t * this_gen)597 static int demux_flac_send_chunk(demux_plugin_t *this_gen) {
598   demux_flac_t *this = (demux_flac_t *) this_gen;
599   buf_element_t *buf = NULL;
600 #ifdef USE_FRAME_BUF
601   int l;
602 #else
603   int64_t input_time_guess;
604 #endif
605 
606 #ifdef USE_FRAME_BUF
607   l = flac_get_frame (this);
608   if (l) {
609     uint32_t flags, normpos = 0;
610     uint8_t *p;
611     int64_t  pts;
612     int      itime;
613 
614     if (this->data_size > 0)
615       normpos = (double)(this->frame1.filepos - this->data_start) * 65535 / this->data_size;
616 
617     if (this->frame1.rate) {
618       if (this->frame1.vbs)
619         pts = (double)this->frame1.num * 90000 / this->frame1.rate;
620       else
621         pts = (double)this->frame1.num * this->frame1.bsize * 90000 / this->frame1.rate;
622       itime = pts / 90;
623     } else {
624       pts = 0;
625       itime = 0;
626     }
627 
628     if (this->seek_flag) {
629       _x_demux_control_newpts (this->stream, pts, BUF_FLAG_SEEK);
630       this->seek_flag = 0;
631     } else {
632       int64_t diff = pts - this->last_pts;
633       if (diff < 0)
634         diff = -diff;
635       if (diff > 220000)
636         _x_demux_control_newpts (this->stream, pts, 0);
637     }
638     this->last_pts = pts;
639 
640     this->read_errs = 3;
641     flags = BUF_FLAG_FRAME_START;
642     p = this->frame_buf + this->frame1.buf_pos;
643     while (l) {
644       buf = this->audio_fifo->buffer_pool_size_alloc (this->audio_fifo, l);
645       buf->type = BUF_AUDIO_FLAC;
646       buf->size = l > buf->max_size ? buf->max_size : l;
647       memcpy (buf->content, p, buf->size);
648       p += buf->size;
649       l -= buf->size;
650       if (!l)
651         flags |= BUF_FLAG_FRAME_END;
652       buf->decoder_flags |= flags;
653       flags &= ~BUF_FLAG_FRAME_START;
654       buf->extra_info->input_normpos = normpos;
655       buf->pts = pts;
656       buf->extra_info->input_time = itime;
657       pts = 0;
658       itime = 0;
659       this->audio_fifo->put (this->audio_fifo, buf);
660     }
661   } else if (!this->seek_flag) {
662     if (--this->read_errs < 0)
663       this->status = DEMUX_FINISHED;
664   }
665 #else
666   /* just send a buffer-sized chunk; let the decoder figure out the
667    * boundaries and let the engine figure out the pts */
668   buf = this->audio_fifo->buffer_pool_alloc (this->audio_fifo);
669   buf->type = BUF_AUDIO_FLAC;
670   if( this->data_size )
671     buf->extra_info->input_normpos = (int) ( (double) (this->input->get_current_pos(this->input) -
672                                      this->data_start) * 65535 / this->data_size );
673   buf->pts = 0;
674   buf->size = buf->max_size;
675 
676   /*
677    * Estimate the input_time field based on file position:
678    *
679    *   current_pos     input time
680    *   -----------  =  ----------
681    *    total_pos      total time
682    *
683    *  total time = total samples / sample rate * 1000
684    */
685 
686   /* do this one step at a time to make sure all the numbers stay safe */
687   if (this->sample_rate) {
688     input_time_guess = this->total_samples;
689     input_time_guess /= this->sample_rate;
690     input_time_guess *= 1000;
691     input_time_guess *= buf->extra_info->input_normpos;
692     input_time_guess /= 65535;
693     buf->extra_info->input_time = input_time_guess;
694   }
695 
696   if (this->input->read(this->input, buf->content, buf->size) !=
697     buf->size) {
698     buf->free_buffer(buf);
699     this->status = DEMUX_FINISHED;
700     return this->status;
701   }
702   buf->decoder_flags |= BUF_FLAG_FRAME_END;
703   this->audio_fifo->put(this->audio_fifo, buf);
704 #endif
705   return this->status;
706 }
707 
demux_flac_send_headers(demux_plugin_t * this_gen)708 static void demux_flac_send_headers(demux_plugin_t *this_gen) {
709   demux_flac_t *this = (demux_flac_t *) this_gen;
710   buf_element_t *buf;
711   xine_waveformatex wave;
712   int bits;
713 
714   memset(&wave, 0, sizeof(wave));
715 
716   this->audio_fifo  = this->stream->audio_fifo;
717 
718   /* send start buffers */
719   _x_demux_control_start(this->stream);
720 
721   if ( ! this->audio_fifo )
722   {
723     this->status = DEMUX_FINISHED;
724     return;
725   }
726 
727   /* lie about 24bps */
728   bits = this->bits_per_sample > 16 ? 16 : this->bits_per_sample;
729 
730   buf = this->audio_fifo->buffer_pool_alloc (this->audio_fifo);
731   buf->type = BUF_AUDIO_FLAC;
732   buf->decoder_flags = BUF_FLAG_HEADER|BUF_FLAG_STDHEADER|BUF_FLAG_FRAME_END;
733   buf->decoder_info[0] = 0;
734   buf->decoder_info[1] = this->sample_rate;
735   buf->decoder_info[2] = bits;
736   buf->decoder_info[3] = this->channels;
737   /* copy the faux WAV header */
738   buf->size = sizeof(xine_waveformatex) + FLAC_STREAMINFO_SIZE;
739   memcpy(buf->content, this->streaminfo, buf->size);
740   /* forge a WAV header with the proper length */
741   wave.cbSize = FLAC_STREAMINFO_SIZE;
742   memcpy(buf->content, &wave, sizeof(xine_waveformatex));
743   this->audio_fifo->put (this->audio_fifo, buf);
744 
745   _x_stream_info_set(this->stream, XINE_STREAM_INFO_HAS_VIDEO, 0);
746   _x_stream_info_set(this->stream, XINE_STREAM_INFO_HAS_AUDIO, 1);
747   _x_stream_info_set(this->stream, XINE_STREAM_INFO_AUDIO_CHANNELS,
748                        this->channels);
749   _x_stream_info_set(this->stream, XINE_STREAM_INFO_AUDIO_SAMPLERATE,
750                        this->sample_rate);
751   _x_stream_info_set(this->stream, XINE_STREAM_INFO_AUDIO_BITS,
752                        bits);
753 
754   this->status = DEMUX_OK;
755 }
756 
demux_flac_seek(demux_plugin_t * this_gen,off_t start_pos,int start_time,int playing)757 static int demux_flac_seek (demux_plugin_t *this_gen,
758                             off_t start_pos, int start_time, int playing) {
759   demux_flac_t *this = (demux_flac_t *) this_gen;
760   int seekpoint_index = 0;
761   int64_t start_pts;
762 #ifndef USE_FRAME_BUF
763   unsigned char buf[4];
764 #endif
765 
766   start_pos = (off_t) ( (double) start_pos / 65535 *
767               this->data_size );
768 
769   /* if thread is not running, initialize demuxer */
770   if( !playing && !start_pos) {
771 
772     /* send new pts */
773     _x_demux_control_newpts(this->stream, 0, 0);
774 
775     this->status = DEMUX_OK;
776   } else {
777 
778     if (this->seekpoints == NULL && !start_pos) {
779       /* cannot seek if there is no seekpoints */
780       this->status = DEMUX_OK;
781       return this->status;
782     }
783 
784     /* Don't use seekpoints if start_pos != 0. This allows smooth seeking */
785     if (start_pos) {
786       /* offset-based seek */
787       this->status = DEMUX_OK;
788       start_pos += this->data_start;
789       this->input->seek(this->input, start_pos, SEEK_SET);
790 #ifdef USE_FRAME_BUF
791       flac_reset_head (this);
792       this->seek_flag = 1;
793 #else
794       while(1){ /* here we try to find something that resembles a frame header */
795 
796 	if (this->input->read(this->input, buf, 2) != 2){
797 	  this->status = DEMUX_FINISHED; /* we sought past the end of stream ? */
798 	  break;
799 	}
800 
801 	if (buf[0] == 0xff && buf[1] == 0xf8)
802 	  break; /* this might be the frame header... or it may be not. We pass it to the decoder
803 		  * to decide, but this way we reduce the number of warnings */
804 	start_pos +=2;
805       }
806 #endif
807       _x_demux_flush_engine(this->stream);
808       this->input->seek(this->input, start_pos, SEEK_SET);
809       _x_demux_control_newpts(this->stream, 0, BUF_FLAG_SEEK);
810       return this->status;
811 
812     } else {
813 #ifdef USE_FRAME_BUF
814       flac_reset_head (this);
815       this->seek_flag = 1;
816 #endif
817       /* do a lazy, linear seek based on the assumption that there are not
818        * that many seek points; time-based seek */
819       start_pts = start_time;
820       start_pts *= 90;
821       if (start_pts < this->seekpoints[0].pts)
822         seekpoint_index = 0;
823       else {
824         for (seekpoint_index = 0; seekpoint_index < this->seekpoint_count - 1;
825           seekpoint_index++) {
826           if (start_pts < this->seekpoints[seekpoint_index + 1].pts) {
827             break;
828           }
829         }
830       }
831     }
832 
833     _x_demux_flush_engine(this->stream);
834     this->input->seek(this->input, this->seekpoints[seekpoint_index].offset,
835       SEEK_SET);
836     _x_demux_control_newpts(this->stream,
837       this->seekpoints[seekpoint_index].pts, BUF_FLAG_SEEK);
838   }
839 
840   return this->status;
841 }
842 
demux_flac_dispose(demux_plugin_t * this_gen)843 static void demux_flac_dispose (demux_plugin_t *this_gen) {
844   demux_flac_t *this = (demux_flac_t *) this_gen;
845 
846   free(this->seekpoints);
847 #ifdef USE_FRAME_BUF
848   free (this->frame_buf);
849 #endif
850   free(this);
851 }
852 
demux_flac_get_status(demux_plugin_t * this_gen)853 static int demux_flac_get_status (demux_plugin_t *this_gen) {
854   demux_flac_t *this = (demux_flac_t *) this_gen;
855 
856   return this->status;
857 }
858 
demux_flac_get_stream_length(demux_plugin_t * this_gen)859 static int demux_flac_get_stream_length (demux_plugin_t *this_gen) {
860   demux_flac_t *this = (demux_flac_t *) this_gen;
861   int64_t length = this->total_samples;
862 
863   if (!this->sample_rate)
864     return 0;
865 
866   length *= 1000;
867   length /= this->sample_rate;
868 
869   return length;
870 }
871 
demux_flac_get_capabilities(demux_plugin_t * this_gen)872 static uint32_t demux_flac_get_capabilities(demux_plugin_t *this_gen) {
873   (void)this_gen;
874   return DEMUX_CAP_NOCAP;
875 }
876 
demux_flac_get_optional_data(demux_plugin_t * this_gen,void * data,int data_type)877 static int demux_flac_get_optional_data(demux_plugin_t *this_gen,
878                                         void *data, int data_type) {
879   (void)this_gen;
880   (void)data;
881   (void)data_type;
882   return DEMUX_OPTIONAL_UNSUPPORTED;
883 }
884 
open_plugin(demux_class_t * class_gen,xine_stream_t * stream,input_plugin_t * input)885 static demux_plugin_t *open_plugin (demux_class_t *class_gen, xine_stream_t *stream,
886                                     input_plugin_t *input) {
887 
888   demux_flac_t    *this;
889 
890   /* this should change eventually... */
891   if (!INPUT_IS_SEEKABLE(input)) {
892     xprintf(stream->xine, XINE_VERBOSITY_DEBUG, "input not seekable, can not handle!\n");
893     return NULL;
894   }
895 
896   this = calloc(1, sizeof(demux_flac_t));
897   if (!this)
898     return NULL;
899 #ifndef HAVE_ZERO_SAFE_MEM
900 #  ifdef USE_FRAME_BUF
901   this->frame_buf_filepos = 0;
902   this->frame_buf_used    = 0;
903   this->frame2.filepos    = 0;
904   this->frame2.rate       = 0;
905   this->frame2.bits       = 0;
906   this->frame2.channels   = 0;
907   this->frame2.vbs        = 0;
908   this->frame2.bsize      = 0;
909   this->frame2.num        = 0;
910   this->frame2.max_size   = 0;
911   this->frame2.buf_pos    = 0;
912   this->last_pts          = 0;
913   this->seek_flag         = 0;
914 #  endif
915   this->seekpoints        = NULL;
916 #endif
917 
918 #ifdef USE_FRAME_BUF
919   this->frame_buf_size = 8 << 10;
920   this->frame_buf      = malloc (this->frame_buf_size + 16);
921   if (!this->frame_buf) {
922     free (this);
923     return NULL;
924   }
925   flac_init_frame_head (this);
926   this->read_errs = 3;
927 #endif
928 
929   this->stream = stream;
930   this->input  = input;
931 
932   this->demux_plugin.send_headers      = demux_flac_send_headers;
933   this->demux_plugin.send_chunk        = demux_flac_send_chunk;
934   this->demux_plugin.seek              = demux_flac_seek;
935   this->demux_plugin.dispose           = demux_flac_dispose;
936   this->demux_plugin.get_status        = demux_flac_get_status;
937   this->demux_plugin.get_stream_length = demux_flac_get_stream_length;
938   this->demux_plugin.get_capabilities  = demux_flac_get_capabilities;
939   this->demux_plugin.get_optional_data = demux_flac_get_optional_data;
940   this->demux_plugin.demux_class       = class_gen;
941 
942   this->status = DEMUX_FINISHED;
943 
944   switch (stream->content_detection_method) {
945 
946   case METHOD_BY_MRL:
947   case METHOD_BY_CONTENT:
948   case METHOD_EXPLICIT:
949 
950     if (!open_flac_file(this)) {
951       demux_flac_dispose (&this->demux_plugin);
952       return NULL;
953     }
954 
955   break;
956 
957   default:
958 #ifdef USE_FRAME_BUF
959     free (this->frame_buf);
960 #endif
961     free (this);
962     return NULL;
963   }
964 
965   return &this->demux_plugin;
966 }
967 
demux_flac_init_plugin(xine_t * xine,const void * data)968 void *demux_flac_init_plugin (xine_t *xine, const void *data) {
969 
970   (void)xine;
971   (void)data;
972 
973   static const demux_class_t demux_flac_class = {
974     .open_plugin     = open_plugin,
975     .description     = N_("Free Lossless Audio Codec (flac) demux plugin"),
976     .identifier      = "FLAC",
977     .mimetypes       =
978       "audio/x-flac: flac: FLAC Audio;"
979       "audio/flac: flac: FLAC Audio;",
980     .extensions      = "flac",
981     .dispose         = NULL,
982   };
983 
984   return (void *)&demux_flac_class;
985 }
986 
987 
988