52850562f5f9f7e186277306f72034af8eb1ca13
[vlc.git] / modules / demux / flac.c
1 /*****************************************************************************
2  * flac.c : FLAC demux module for vlc
3  *****************************************************************************
4  * Copyright (C) 2001-2008 VLC authors and VideoLAN
5  *
6  * Authors: Gildas Bazin <gbazin@netcourrier.com>
7  *          Laurent Aimar <fenrir@via.ecp.fr>
8  *
9  * This program is free software; you can redistribute it and/or modify it
10  * under the terms of the GNU Lesser General Public License as published by
11  * the Free Software Foundation; either version 2.1 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <vlc_common.h>
32 #include <vlc_plugin.h>
33 #include <vlc_demux.h>
34 #include <vlc_meta.h>                 /* vlc_meta_* */
35 #include <vlc_input.h>                /* vlc_input_attachment, vlc_seekpoint */
36 #include <vlc_codec.h>                /* decoder_t */
37 #include <vlc_charset.h>              /* EnsureUTF8 */
38
39 #include <assert.h>
40 #include <limits.h>
41 #include "xiph_metadata.h"            /* vorbis comments */
42 #include "../packetizer/flac.h"
43
44 /*****************************************************************************
45  * Module descriptor
46  *****************************************************************************/
47 static int  Open  ( vlc_object_t * );
48 static void Close ( vlc_object_t * );
49
50 vlc_module_begin ()
51     set_description( N_("FLAC demuxer") )
52     set_capability( "demux", 155 )
53     set_category( CAT_INPUT )
54     set_subcategory( SUBCAT_INPUT_DEMUX )
55     set_callbacks( Open, Close )
56     add_shortcut( "flac" )
57     add_file_extension("flac")
58 vlc_module_end ()
59
60 /*****************************************************************************
61  * Local prototypes
62  *****************************************************************************/
63 static int Demux  ( demux_t * );
64 static int Control( demux_t *, int, va_list );
65
66 static int  ParseHeaders( demux_t *, es_format_t * );
67
68 typedef struct
69 {
70     vlc_tick_t  i_time_offset;
71     uint64_t i_byte_offset;
72 } flac_seekpoint_t;
73
74 typedef struct
75 {
76     bool  b_start;
77     int   i_next_block_flags;
78     es_out_id_t *p_es;
79     block_t *p_current_block;
80
81     /* Packetizer */
82     decoder_t *p_packetizer;
83
84     vlc_meta_t *p_meta;
85
86     vlc_tick_t i_pts;
87     struct flac_stream_info stream_info;
88     bool b_stream_info;
89
90     vlc_tick_t i_length; /* Length from stream info */
91     uint64_t i_data_pos;
92
93     /* */
94     int         i_seekpoint;
95     flac_seekpoint_t **seekpoint;
96
97     /* title/chapters seekpoints */
98     int           i_title_seekpoints;
99     seekpoint_t **pp_title_seekpoints;
100
101     /* */
102     int                i_attachments;
103     input_attachment_t **attachments;
104     int                i_cover_idx;
105     int                i_cover_score;
106 } demux_sys_t;
107
108 #define FLAC_PACKET_SIZE 16384
109 #define FLAC_MAX_PREROLL      VLC_TICK_FROM_SEC(4)
110 #define FLAC_MAX_SLOW_PREROLL VLC_TICK_FROM_SEC(45)
111
112 /*****************************************************************************
113  * Open: initializes ES structures
114  *****************************************************************************/
115 static int Open( vlc_object_t * p_this )
116 {
117     demux_t     *p_demux = (demux_t*)p_this;
118     demux_sys_t *p_sys;
119     const uint8_t *p_peek;
120     es_format_t fmt;
121
122     /* Have a peep at the show. */
123     if( vlc_stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC;
124
125     if( p_peek[0]!='f' || p_peek[1]!='L' || p_peek[2]!='a' || p_peek[3]!='C' )
126     {
127         if( !p_demux->obj.force
128          && !demux_IsContentType( p_demux, "audio/flac" ) )
129             return VLC_EGENERIC;
130
131         /* User forced */
132         msg_Err( p_demux, "this doesn't look like a flac stream, "
133                  "continuing anyway" );
134     }
135
136     p_sys = malloc( sizeof( demux_sys_t ) );
137     if( unlikely(p_sys == NULL) )
138         return VLC_ENOMEM;
139
140     p_demux->pf_demux   = Demux;
141     p_demux->pf_control = Control;
142     p_demux->p_sys      = p_sys;
143     p_sys->b_start = true;
144     p_sys->i_next_block_flags = 0;
145     p_sys->p_packetizer = NULL;
146     p_sys->p_meta = NULL;
147     p_sys->i_length = 0;
148     p_sys->i_pts = VLC_TICK_INVALID;
149     p_sys->b_stream_info = false;
150     p_sys->p_es = NULL;
151     p_sys->p_current_block = NULL;
152     TAB_INIT( p_sys->i_seekpoint, p_sys->seekpoint );
153     TAB_INIT( p_sys->i_attachments, p_sys->attachments);
154     TAB_INIT( p_sys->i_title_seekpoints, p_sys->pp_title_seekpoints );
155     p_sys->i_cover_idx = 0;
156     p_sys->i_cover_score = 0;
157
158     es_format_Init( &fmt, AUDIO_ES, VLC_CODEC_FLAC );
159
160     /* We need to read and store the STREAMINFO metadata into fmt extra */
161     if( ParseHeaders( p_demux, &fmt ) )
162         goto error;
163
164     /* Load the FLAC packetizer */
165     p_sys->p_packetizer = demux_PacketizerNew( p_demux, &fmt, "flac" );
166     if( !p_sys->p_packetizer )
167         goto error;
168
169     if( p_sys->i_cover_idx < p_sys->i_attachments )
170     {
171         char psz_url[128];
172         if( !p_sys->p_meta )
173             p_sys->p_meta = vlc_meta_New();
174         snprintf( psz_url, sizeof(psz_url), "attachment://%s",
175                   p_sys->attachments[p_sys->i_cover_idx]->psz_name );
176         vlc_meta_Set( p_sys->p_meta, vlc_meta_ArtworkURL, psz_url );
177     }
178
179     p_sys->p_packetizer->fmt_in.i_id = 0;
180     p_sys->p_es = es_out_Add( p_demux->out, &p_sys->p_packetizer->fmt_in );
181     if( !p_sys->p_es )
182         goto error;
183
184     return VLC_SUCCESS;
185 error:
186     Close( p_this );
187     return VLC_EGENERIC;
188 }
189
190 /*****************************************************************************
191  * Close: frees unused data
192  *****************************************************************************/
193 static void Close( vlc_object_t * p_this )
194 {
195     demux_t     *p_demux = (demux_t*)p_this;
196     demux_sys_t *p_sys = p_demux->p_sys;
197
198     if( p_sys->p_current_block )
199         block_Release( p_sys->p_current_block );
200
201     for( int i = 0; i < p_sys->i_seekpoint; i++ )
202         free(p_sys->seekpoint[i]);
203     TAB_CLEAN( p_sys->i_seekpoint, p_sys->seekpoint );
204
205     for( int i = 0; i < p_sys->i_attachments; i++ )
206         vlc_input_attachment_Release( p_sys->attachments[i] );
207     TAB_CLEAN( p_sys->i_attachments, p_sys->attachments);
208
209     for( int i = 0; i < p_sys->i_title_seekpoints; i++ )
210         vlc_seekpoint_Delete( p_sys->pp_title_seekpoints[i] );
211     TAB_CLEAN( p_sys->i_title_seekpoints, p_sys->pp_title_seekpoints );
212
213     /* Delete the decoder */
214     if( p_sys->p_packetizer )
215         demux_PacketizerDestroy( p_sys->p_packetizer );
216
217     if( p_sys->p_meta )
218         vlc_meta_Delete( p_sys->p_meta );
219     free( p_sys );
220 }
221
222 static block_t *GetPacketizedBlock( decoder_t *p_packetizer,
223                                     const struct flac_stream_info *streaminfo,
224                                     block_t **pp_current_block )
225 {
226     block_t *p_block = p_packetizer->pf_packetize( p_packetizer, pp_current_block );
227     if( p_block )
228     {
229         if( p_block->i_buffer >= FLAC_HEADER_SIZE_MIN && p_block->i_buffer < INT_MAX )
230         {
231             struct flac_header_info headerinfo = { .i_pts = VLC_TICK_INVALID };
232             int i_ret = FLAC_ParseSyncInfo( p_block->p_buffer, p_block->i_buffer,
233                                             streaminfo, NULL, &headerinfo );
234             assert( i_ret != 0 ); /* Same as packetizer */
235             /* Use Frame PTS, not the interpolated one */
236             p_block->i_dts = p_block->i_pts = headerinfo.i_pts;
237         }
238     }
239     return p_block;
240 }
241
242 static void FlushPacketizer( decoder_t *p_packetizer )
243 {
244     if( p_packetizer->pf_flush )
245         p_packetizer->pf_flush( p_packetizer );
246     else
247     {
248         block_t *p_block_out;
249         while( (p_block_out = p_packetizer->pf_packetize( p_packetizer, NULL )) )
250             block_Release( p_block_out );
251     }
252 }
253
254 static void Reset( demux_sys_t *p_sys )
255 {
256     p_sys->i_pts = VLC_TICK_INVALID;
257
258     FlushPacketizer( p_sys->p_packetizer );
259     if( p_sys->p_current_block )
260     {
261         block_Release( p_sys->p_current_block );
262         p_sys->p_current_block = NULL;
263     }
264 }
265
266 static int RefineSeek( demux_t *p_demux, vlc_tick_t i_time, double i_bytemicrorate,
267                        uint64_t i_lowpos, uint64_t i_highpos )
268 {
269     demux_sys_t *p_sys = p_demux->p_sys;
270     bool b_found = false;
271     block_t *p_block_out;
272     block_t *p_block_in;
273
274     unsigned i_frame_size = FLAC_FRAME_SIZE_MIN;
275
276     bool b_canfastseek = false;
277     vlc_stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &b_canfastseek );
278
279     uint64_t i_start_pos = vlc_stream_Tell( p_demux->s );
280
281     while( !b_found )
282     {
283         FlushPacketizer( p_sys->p_packetizer );
284
285         p_block_out = NULL;
286         p_block_in = NULL;
287
288         while( !p_block_out )
289         {
290             if( !p_block_in )
291             {
292                 if( !(p_block_in = vlc_stream_Block( p_demux->s, i_frame_size )) )
293                     break;
294             }
295
296             p_block_out = GetPacketizedBlock( p_sys->p_packetizer,
297                                               p_sys->b_stream_info ? &p_sys->stream_info : NULL,
298                                              &p_block_in );
299         }
300
301         if( !p_block_out )
302         {
303             if( p_block_in )
304                 block_Release( p_block_in );
305             break;
306         }
307
308         if( p_block_out->i_buffer > i_frame_size )
309             i_frame_size = p_block_out->i_buffer;
310
311         /* If we are further than wanted block */
312         if( p_block_out->i_dts >= i_time )
313         {
314             vlc_tick_t i_diff = p_block_out->i_dts - i_time;
315             /* Not in acceptable approximation range */
316             if( i_diff > VLC_TICK_FROM_MS(100) && i_diff / i_bytemicrorate > i_frame_size )
317             {
318                 i_highpos = i_start_pos;
319                 i_start_pos -= ( i_diff / i_bytemicrorate );
320                 i_start_pos = __MAX(i_start_pos, i_lowpos + i_frame_size);
321             }
322             else b_found = true;
323         }
324         else
325         {
326             vlc_tick_t i_diff = i_time - p_block_out->i_dts;
327             /* Not in acceptable NEXT_TIME demux range */
328             if( i_diff >= ((b_canfastseek) ? FLAC_MAX_PREROLL : FLAC_MAX_SLOW_PREROLL) &&
329                 i_diff / i_bytemicrorate > i_frame_size )
330             {
331                 i_lowpos = i_start_pos;
332                 i_start_pos += ( i_diff / i_bytemicrorate );
333                 i_start_pos = __MIN(i_start_pos, i_highpos - i_frame_size);
334             }
335             else b_found = true;
336         }
337
338         if( p_block_out )
339             block_Release( p_block_out );
340         if( p_block_in )
341             block_Release( p_block_in );
342
343         if( !b_found )
344         {
345             if( i_highpos < i_lowpos || i_highpos - i_lowpos < i_frame_size )
346                 break;
347
348             if( VLC_SUCCESS != vlc_stream_Seek( p_demux->s, i_start_pos ) )
349                 break;
350         }
351     }
352
353     return b_found ? VLC_SUCCESS : VLC_EGENERIC;
354 }
355
356 /*****************************************************************************
357  * Demux: reads and demuxes data packets
358  *****************************************************************************
359  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
360  *****************************************************************************/
361 static int Demux( demux_t *p_demux )
362 {
363     demux_sys_t *p_sys = p_demux->p_sys;
364     block_t *p_block_out;
365
366     bool b_eof = false;
367     if( p_sys->p_current_block == NULL )
368     {
369         p_sys->p_current_block = vlc_stream_Block( p_demux->s, FLAC_PACKET_SIZE );
370         b_eof = (p_sys->p_current_block == NULL);
371     }
372
373     if ( p_sys->p_current_block )
374     {
375         p_sys->p_current_block->i_flags = p_sys->i_next_block_flags;
376         p_sys->i_next_block_flags = 0;
377         p_sys->p_current_block->i_pts =
378         p_sys->p_current_block->i_dts = p_sys->b_start ? VLC_TICK_0 : VLC_TICK_INVALID;
379     }
380
381     while( (p_block_out = GetPacketizedBlock( p_sys->p_packetizer,
382                             p_sys->b_stream_info ? &p_sys->stream_info : NULL,
383                             p_sys->p_current_block ? &p_sys->p_current_block : NULL ) ) )
384     {
385         /* Only clear on output when packet is accepted as sync #17111 */
386         p_sys->b_start = false;
387         while( p_block_out )
388         {
389             block_t *p_next = p_block_out->p_next;
390
391             p_block_out->p_next = NULL;
392
393             /* set PCR */
394             if( unlikely(p_sys->i_pts == VLC_TICK_INVALID) )
395                 es_out_SetPCR( p_demux->out, __MAX(p_block_out->i_dts - 1, VLC_TICK_0) );
396
397             if(p_block_out->i_dts != VLC_TICK_INVALID)
398                 p_sys->i_pts = p_block_out->i_dts;
399
400             es_out_Send( p_demux->out, p_sys->p_es, p_block_out );
401
402             es_out_SetPCR( p_demux->out, p_sys->i_pts );
403
404             p_block_out = p_next;
405         }
406         break;
407     }
408
409     return b_eof ? VLC_DEMUXER_EOF : VLC_DEMUXER_SUCCESS;
410 }
411
412 /*****************************************************************************
413  * Control:
414  *****************************************************************************/
415 static vlc_tick_t ControlGetLength( demux_t *p_demux )
416 {
417     demux_sys_t *p_sys = p_demux->p_sys;
418     const uint64_t i_size = stream_Size(p_demux->s) - p_sys->i_data_pos;
419     vlc_tick_t i_length = p_sys->i_length;
420     int i;
421
422     /* Try to fix length using seekpoint and current size for truncated file */
423     for( i = p_sys->i_seekpoint-1; i >= 0; i-- )
424     {
425         flac_seekpoint_t *s = p_sys->seekpoint[i];
426         if( s->i_byte_offset <= i_size )
427         {
428             if( i+1 < p_sys->i_seekpoint )
429             {
430                 /* Broken file */
431                 flac_seekpoint_t *n = p_sys->seekpoint[i+1];
432                 assert( n->i_byte_offset != s->i_byte_offset); /* Should be ensured by ParseSeekTable */
433                 i_length = s->i_time_offset + (n->i_time_offset-s->i_time_offset) * (i_size-s->i_byte_offset) / (n->i_byte_offset-s->i_byte_offset);
434             }
435             break;
436         }
437     }
438     return i_length;
439 }
440
441 static vlc_tick_t ControlGetTime( demux_t *p_demux )
442 {
443     demux_sys_t *p_sys = p_demux->p_sys;
444     return p_sys->i_pts;
445 }
446
447 static int ControlSetTime( demux_t *p_demux, vlc_tick_t i_time )
448 {
449     demux_sys_t *p_sys = p_demux->p_sys;
450     bool b_seekable;
451     int i;
452
453     /* */
454     vlc_stream_Control( p_demux->s, STREAM_CAN_SEEK, &b_seekable );
455     if( !b_seekable )
456         return VLC_EGENERIC;
457
458     const vlc_tick_t i_length = ControlGetLength( p_demux );
459     if( i_length <= 0 )
460         return VLC_EGENERIC;
461
462     const uint64_t i_stream_size = stream_Size( p_demux->s );
463     if( i_stream_size <= p_sys->i_data_pos )
464         return VLC_EGENERIC;
465
466     const double i_bytemicrorate = (double) i_length / (i_stream_size - p_sys->i_data_pos);
467     if( i_bytemicrorate == 0 )
468         return VLC_EGENERIC;
469
470     uint64_t i_lower = p_sys->i_data_pos;
471     uint64_t i_upper = i_stream_size;
472     uint64_t i_start_pos;
473
474     assert( p_sys->i_seekpoint > 0 );   /* ReadMeta ensure at least (0,0) */
475     if( p_sys->i_seekpoint > 1 )
476     {
477         /* lookup base offset */
478         for( i = p_sys->i_seekpoint-1; i >= 0; i-- )
479         {
480             if( p_sys->seekpoint[i]->i_time_offset <= i_time )
481                 break;
482         }
483
484         i_lower = p_sys->seekpoint[0]->i_byte_offset + p_sys->i_data_pos;
485         if( i+1 < p_sys->i_seekpoint )
486             i_upper = p_sys->seekpoint[i+1]->i_byte_offset + p_sys->i_data_pos;
487
488         i_start_pos = i_lower;
489     }
490     else
491     {
492         i_start_pos = i_time / i_bytemicrorate;
493     }
494
495     if( VLC_SUCCESS != vlc_stream_Seek( p_demux->s, i_start_pos ) )
496         return VLC_EGENERIC;
497
498     int i_ret = RefineSeek( p_demux, i_time, i_bytemicrorate, i_lower, i_upper );
499     if( i_ret == VLC_SUCCESS )
500     {
501         p_sys->i_next_block_flags |= BLOCK_FLAG_DISCONTINUITY;
502         Reset( p_sys );
503         es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, i_time );
504     }
505
506     return i_ret;
507 }
508
509 static int Control( demux_t *p_demux, int i_query, va_list args )
510 {
511     demux_sys_t *p_sys = p_demux->p_sys;
512
513     if( i_query == DEMUX_GET_META )
514     {
515         vlc_meta_t *p_meta = va_arg( args, vlc_meta_t * );
516         if( p_sys->p_meta )
517             vlc_meta_Merge( p_meta, p_sys->p_meta );
518         return VLC_SUCCESS;
519     }
520     else if( i_query == DEMUX_HAS_UNSUPPORTED_META )
521     {
522         bool *pb_bool = va_arg( args, bool* );
523         *pb_bool = true;
524         return VLC_SUCCESS;
525     }
526     else if( i_query == DEMUX_GET_LENGTH )
527     {
528         *va_arg( args, vlc_tick_t * ) = ControlGetLength( p_demux );
529         return VLC_SUCCESS;
530     }
531     else if( i_query == DEMUX_SET_TIME )
532     {
533         return ControlSetTime( p_demux, va_arg( args, vlc_tick_t ) );
534     }
535     else if( i_query == DEMUX_SET_POSITION )
536     {
537         const double f = va_arg( args, double );
538         vlc_tick_t i_length = ControlGetLength( p_demux );
539         int i_ret;
540         if( i_length > 0 )
541         {
542             i_ret = ControlSetTime( p_demux, i_length * f );
543             if( i_ret == VLC_SUCCESS )
544                 return i_ret;
545         }
546         /* just byte pos seek */
547         i_ret = vlc_stream_Seek( p_demux->s, (int64_t) (f * stream_Size( p_demux->s )) );
548         if( i_ret == VLC_SUCCESS )
549         {
550             p_sys->i_next_block_flags |= BLOCK_FLAG_DISCONTINUITY;
551             Reset( p_sys );
552         }
553         return i_ret;
554     }
555     else if( i_query == DEMUX_GET_TIME )
556     {
557         *va_arg( args, vlc_tick_t * ) = ControlGetTime( p_demux );
558         return VLC_SUCCESS;
559     }
560     else if( i_query == DEMUX_GET_POSITION )
561     {
562         const vlc_tick_t i_length = ControlGetLength(p_demux);
563         if( i_length > 0 )
564         {
565             vlc_tick_t current = ControlGetTime(p_demux);
566             if( current <= i_length )
567             {
568                 *(va_arg( args, double * )) = (double)current / (double)i_length;
569                 return VLC_SUCCESS;
570             }
571         }
572         /* Else fallback on byte position */
573     }
574     else if( i_query == DEMUX_GET_ATTACHMENTS )
575     {
576         input_attachment_t ***ppp_attach =
577             va_arg( args, input_attachment_t *** );
578         int *pi_int = va_arg( args, int * );
579
580         if( p_sys->i_attachments <= 0 )
581             return VLC_EGENERIC;
582
583         *ppp_attach = vlc_alloc( p_sys->i_attachments, sizeof(input_attachment_t*) );
584         if( !*ppp_attach )
585             return VLC_EGENERIC;
586         *pi_int = p_sys->i_attachments;
587         for( int i = 0; i < p_sys->i_attachments; i++ )
588             (*ppp_attach)[i] = vlc_input_attachment_Hold( p_sys->attachments[i] );
589         return VLC_SUCCESS;
590     }
591     else if( i_query == DEMUX_GET_TITLE_INFO )
592     {
593         input_title_t ***ppp_title = va_arg( args, input_title_t *** );
594         int *pi_int = va_arg( args, int * );
595         int *pi_title_offset = va_arg( args, int * );
596         int *pi_seekpoint_offset = va_arg( args, int * );
597
598         if( !p_sys->i_title_seekpoints )
599             return VLC_EGENERIC;
600
601         *pi_int = 1;
602         *ppp_title = malloc( sizeof(input_title_t*) );
603         if(!*ppp_title)
604             return VLC_EGENERIC;
605
606         input_title_t *p_title = (*ppp_title)[0] = vlc_input_title_New();
607         if(!p_title)
608         {
609             free(*ppp_title);
610             return VLC_EGENERIC;
611         }
612
613         p_title->seekpoint = vlc_alloc( p_sys->i_title_seekpoints, sizeof(seekpoint_t*) );
614         if(!p_title->seekpoint)
615         {
616             vlc_input_title_Delete(p_title);
617             free(*ppp_title);
618             return VLC_EGENERIC;
619         }
620
621         p_title->i_seekpoint = p_sys->i_title_seekpoints;
622         for( int i = 0; i < p_title->i_seekpoint; i++ )
623             p_title->seekpoint[i] = vlc_seekpoint_Duplicate( p_sys->pp_title_seekpoints[i] );
624
625         *pi_title_offset = 0;
626         *pi_seekpoint_offset = 0;
627
628         return VLC_SUCCESS;
629     }
630     else if( i_query == DEMUX_SET_TITLE )
631     {
632         const int i_title = va_arg( args, int );
633         if( i_title != 0 )
634             return VLC_EGENERIC;
635         return VLC_SUCCESS;
636     }
637     else if( i_query == DEMUX_SET_SEEKPOINT )
638     {
639         const int i_seekpoint = va_arg( args, int );
640         if( !p_sys->i_title_seekpoints || i_seekpoint >= p_sys->i_title_seekpoints )
641             return VLC_EGENERIC;
642         return ControlSetTime( p_demux, p_sys->pp_title_seekpoints[i_seekpoint]->i_time_offset );
643     }
644
645     return demux_vaControlHelper( p_demux->s, p_sys->i_data_pos, -1,
646                                    8*0, 1, i_query, args );
647 }
648
649 enum
650 {
651     META_STREAMINFO = 0,
652     META_SEEKTABLE = 3,
653     META_COMMENT = 4,
654     META_PICTURE = 6,
655 };
656
657 static inline int Get24bBE( const uint8_t *p )
658 {
659     return (p[0] << 16)|(p[1] << 8)|(p[2]);
660 }
661
662 static void ParseSeekTable( demux_t *p_demux, const uint8_t *p_data, size_t i_data,
663                             unsigned i_sample_rate );
664 static void ParseComment( demux_t *, const uint8_t *p_data, size_t i_data );
665 static void ParsePicture( demux_t *, const uint8_t *p_data, size_t i_data );
666
667 static int  ParseHeaders( demux_t *p_demux, es_format_t *p_fmt )
668 {
669     demux_sys_t *p_sys = p_demux->p_sys;
670     ssize_t i_peek;
671     const uint8_t *p_peek;
672     bool b_last;
673
674     /* Be sure we have seekpoint 0 */
675     flac_seekpoint_t *s = xmalloc( sizeof (*s) );
676     s->i_time_offset = 0;
677     s->i_byte_offset = 0;
678     TAB_APPEND( p_sys->i_seekpoint, p_sys->seekpoint, s );
679
680     uint8_t header[4];
681     if( vlc_stream_Read( p_demux->s, header, 4) < 4)
682         return VLC_EGENERIC;
683
684     if (memcmp(header, "fLaC", 4))
685         return VLC_EGENERIC;
686
687     b_last = 0;
688     while( !b_last )
689     {
690         int i_len;
691         int i_type;
692
693         i_peek = vlc_stream_Peek( p_demux->s, &p_peek, 4 );
694         if( i_peek < 4 )
695             break;
696         b_last = p_peek[0]&0x80;
697         i_type = p_peek[0]&0x7f;
698         i_len  = Get24bBE( &p_peek[1] );
699
700         if( i_type == META_STREAMINFO && p_fmt->p_extra == NULL )
701         {
702             if( i_len != FLAC_STREAMINFO_SIZE ) {
703                 msg_Err( p_demux, "invalid size %d for a STREAMINFO metadata block", i_len );
704                 return VLC_EGENERIC;
705             }
706
707             p_fmt->p_extra = malloc( FLAC_STREAMINFO_SIZE );
708             if( p_fmt->p_extra == NULL )
709                 return VLC_EGENERIC;
710
711             if( vlc_stream_Read( p_demux->s, NULL, 4) < 4)
712             {
713                 FREENULL( p_fmt->p_extra );
714                 return VLC_EGENERIC;
715             }
716             if( vlc_stream_Read( p_demux->s, p_fmt->p_extra,
717                                  FLAC_STREAMINFO_SIZE ) != FLAC_STREAMINFO_SIZE )
718             {
719                 msg_Err( p_demux, "failed to read STREAMINFO metadata block" );
720                 FREENULL( p_fmt->p_extra );
721                 return VLC_EGENERIC;
722             }
723             p_fmt->i_extra = FLAC_STREAMINFO_SIZE;
724
725             /* */
726             p_sys->b_stream_info = true;
727             FLAC_ParseStreamInfo( (uint8_t *) p_fmt->p_extra, &p_sys->stream_info );
728
729             p_fmt->audio.i_rate = p_sys->stream_info.sample_rate;
730             p_fmt->audio.i_channels = p_sys->stream_info.channels;
731             p_fmt->audio.i_bitspersample = p_sys->stream_info.bits_per_sample;
732             if( p_sys->stream_info.sample_rate > 0 )
733                 p_sys->i_length = vlc_tick_from_samples(p_sys->stream_info.total_samples,
734                                   p_sys->stream_info.sample_rate);
735
736             continue;
737         }
738         else if( i_type == META_SEEKTABLE )
739         {
740             i_peek = vlc_stream_Peek( p_demux->s, &p_peek, 4+i_len );
741             if( i_peek == 4+i_len )
742                 ParseSeekTable( p_demux, p_peek, i_peek, p_fmt->audio.i_rate );
743         }
744         else if( i_type == META_COMMENT )
745         {
746             i_peek = vlc_stream_Peek( p_demux->s, &p_peek, 4+i_len );
747             if( i_peek == 4+i_len )
748                 ParseComment( p_demux, p_peek, i_peek );
749         }
750         else if( i_type == META_PICTURE )
751         {
752             i_peek = vlc_stream_Peek( p_demux->s, &p_peek, 4+i_len );
753             if( i_peek == 4+i_len )
754                 ParsePicture( p_demux, p_peek, i_peek );
755         }
756
757         if( vlc_stream_Read( p_demux->s, NULL, 4+i_len ) < 4+i_len )
758             break;
759     }
760
761     /* */
762     p_sys->i_data_pos = vlc_stream_Tell( p_demux->s );
763
764     if ( p_fmt->p_extra == NULL )
765         return VLC_EGENERIC;
766
767     return VLC_SUCCESS;
768 }
769
770 static void ParseSeekTable( demux_t *p_demux, const uint8_t *p_data, size_t i_data,
771                             unsigned i_sample_rate )
772 {
773     demux_sys_t *p_sys = p_demux->p_sys;
774     flac_seekpoint_t *s;
775     size_t i;
776
777     if( i_sample_rate == 0 )
778         return;
779
780     /* */
781     for( i = 0; i < (i_data-4)/18; i++ )
782     {
783         const int64_t i_sample = GetQWBE( &p_data[4+18*i+0] );
784         int j;
785
786         if( i_sample < 0 || i_sample >= INT64_MAX ||
787             GetQWBE( &p_data[4+18*i+8] ) < FLAC_STREAMINFO_SIZE )
788             break;
789
790         s = xmalloc( sizeof (*s) );
791         s->i_time_offset = vlc_tick_from_samples(i_sample, i_sample_rate);
792         s->i_byte_offset = GetQWBE( &p_data[4+18*i+8] );
793
794         /* Check for duplicate entry */
795         for( j = 0; j < p_sys->i_seekpoint; j++ )
796         {
797             if( p_sys->seekpoint[j]->i_time_offset == s->i_time_offset ||
798                 p_sys->seekpoint[j]->i_byte_offset == s->i_byte_offset )
799             {
800                 free( s );
801                 s = NULL;
802                 break;
803             }
804         }
805         if( s )
806         {
807             TAB_APPEND( p_sys->i_seekpoint, p_sys->seekpoint, s );
808         }
809     }
810     /* TODO sort it by size and remove wrong seek entry (time not increasing) */
811 }
812
813 static void ParseComment( demux_t *p_demux, const uint8_t *p_data, size_t i_data )
814 {
815     demux_sys_t *p_sys = p_demux->p_sys;
816
817     if( i_data < 4 )
818         return;
819
820     vorbis_ParseComment( NULL, &p_sys->p_meta, &p_data[4], i_data - 4,
821         &p_sys->i_attachments, &p_sys->attachments,
822         &p_sys->i_cover_score, &p_sys->i_cover_idx,
823         &p_sys->i_title_seekpoints, &p_sys->pp_title_seekpoints, NULL, NULL );
824 }
825
826 static void ParsePicture( demux_t *p_demux, const uint8_t *p_data, size_t i_data )
827 {
828     demux_sys_t *p_sys = p_demux->p_sys;
829
830     i_data -= 4; p_data += 4;
831
832     input_attachment_t *p_attachment = ParseFlacPicture( p_data, i_data,
833         p_sys->i_attachments, &p_sys->i_cover_score, &p_sys->i_cover_idx );
834     if( p_attachment == NULL )
835         return;
836
837     TAB_APPEND( p_sys->i_attachments, p_sys->attachments, p_attachment );
838 }