]> git.sesse.net Git - vlc/blob - modules/demux/avformat/demux.c
avformat demux: AVFormatContext->nb_streams == 0 is valid
[vlc] / modules / demux / avformat / demux.c
1 /*****************************************************************************
2  * demux.c: demuxer using libavformat
3  *****************************************************************************
4  * Copyright (C) 2004-2009 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Gildas Bazin <gbazin@videolan.org>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28
29 #ifdef HAVE_CONFIG_H
30 # include "config.h"
31 #endif
32
33 #include <vlc_common.h>
34 #include <vlc_demux.h>
35 #include <vlc_stream.h>
36 #include <vlc_meta.h>
37 #include <vlc_input.h>
38 #include <vlc_charset.h>
39 #include <vlc_avcodec.h>
40
41 #include <libavformat/avformat.h>
42
43 #include "../../codec/avcodec/avcodec.h"
44 #include "../../codec/avcodec/chroma.h"
45 #include "../../codec/avcodec/avcommon.h"
46 #include "avformat.h"
47 #include "../xiph.h"
48 #include "../vobsub.h"
49
50 /* Support for deprecated APIs */
51
52 #if LIBAVFORMAT_VERSION_MAJOR < 54
53 # define AVDictionaryEntry AVMetadataTag
54 # define av_dict_get av_metadata_get
55 #endif
56
57 //#define AVFORMAT_DEBUG 1
58
59 /* Version checking */
60 #if defined(HAVE_FFMPEG_AVFORMAT_H) || defined(HAVE_LIBAVFORMAT_AVFORMAT_H)
61
62 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(50<<8)+0) )
63 #   define HAVE_AVUTIL_CODEC_ATTACHMENT 1
64 #endif
65
66 /*****************************************************************************
67  * demux_sys_t: demux descriptor
68  *****************************************************************************/
69 struct demux_sys_t
70 {
71 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
72     ByteIOContext   io;
73 #endif
74
75     int             io_buffer_size;
76     uint8_t        *io_buffer;
77
78     AVInputFormat  *fmt;
79     AVFormatContext *ic;
80
81     int             i_tk;
82     es_out_id_t     **tk;
83     int64_t         *tk_pcr;
84     int64_t         i_pcr;
85
86     unsigned    i_ssa_order;
87
88     int                i_attachments;
89     input_attachment_t **attachments;
90
91     /* Only one title with seekpoints possible atm. */
92     input_title_t *p_title;
93 };
94
95 /*****************************************************************************
96  * Local prototypes
97  *****************************************************************************/
98 static int Demux  ( demux_t *p_demux );
99 static int Control( demux_t *p_demux, int i_query, va_list args );
100
101 static int IORead( void *opaque, uint8_t *buf, int buf_size );
102 static int64_t IOSeek( void *opaque, int64_t offset, int whence );
103
104 static block_t *BuildSsaFrame( const AVPacket *p_pkt, unsigned i_order );
105 static void UpdateSeekPoint( demux_t *p_demux, int64_t i_time );
106 static void ResetTime( demux_t *p_demux, int64_t i_time );
107
108 /*****************************************************************************
109  * Open
110  *****************************************************************************/
111 int OpenDemux( vlc_object_t *p_this )
112 {
113     demux_t       *p_demux = (demux_t*)p_this;
114     demux_sys_t   *p_sys;
115     AVProbeData   pd;
116     AVInputFormat *fmt = NULL;
117     unsigned int  i;
118     int64_t       i_start_time = -1;
119     bool          b_can_seek;
120     char         *psz_url;
121     int           error;
122
123     if( p_demux->psz_file )
124         psz_url = strdup( p_demux->psz_file );
125     else
126     {
127         if( asprintf( &psz_url, "%s://%s", p_demux->psz_access, p_demux->psz_location ) == -1)
128             return VLC_ENOMEM;
129     }
130     msg_Dbg( p_demux, "trying url: %s", psz_url );
131     /* Init Probe data */
132     pd.filename = psz_url;
133     if( ( pd.buf_size = stream_Peek( p_demux->s, (const uint8_t**)&pd.buf, 2048 + 213 ) ) <= 0 )
134     {
135         free( psz_url );
136         msg_Warn( p_demux, "cannot peek" );
137         return VLC_EGENERIC;
138     }
139     stream_Control( p_demux->s, STREAM_CAN_SEEK, &b_can_seek );
140
141     vlc_init_avformat();
142
143     char *psz_format = var_InheritString( p_this, "avformat-format" );
144     if( psz_format )
145     {
146         if( (fmt = av_find_input_format(psz_format)) )
147             msg_Dbg( p_demux, "forcing format: %s", fmt->name );
148         free( psz_format );
149     }
150
151     /* Guess format */
152     if( !fmt && !( fmt = av_probe_input_format( &pd, 1 ) ) )
153     {
154         msg_Dbg( p_demux, "couldn't guess format" );
155         free( psz_url );
156         return VLC_EGENERIC;
157     }
158
159     if( !p_demux->b_force )
160     {
161         static const char ppsz_blacklist[][16] = {
162             /* Don't handle MPEG unless forced */
163             "mpeg", "vcd", "vob", "mpegts",
164             /* libavformat's redirector won't work */
165             "redir", "sdp",
166             /* Don't handle subtitles format */
167             "ass", "srt", "microdvd",
168             ""
169         };
170
171         for( int i = 0; *ppsz_blacklist[i]; i++ )
172         {
173             if( !strcmp( fmt->name, ppsz_blacklist[i] ) )
174             {
175                 free( psz_url );
176                 return VLC_EGENERIC;
177             }
178         }
179     }
180
181     /* Don't trigger false alarms on bin files */
182     if( !p_demux->b_force && !strcmp( fmt->name, "psxstr" ) )
183     {
184         int i_len;
185
186         if( !p_demux->psz_file )
187         {
188             free( psz_url );
189             return VLC_EGENERIC;
190         }
191
192         i_len = strlen( p_demux->psz_file );
193         if( i_len < 4 )
194         {
195             free( psz_url );
196             return VLC_EGENERIC;
197         }
198
199         if( strcasecmp( &p_demux->psz_file[i_len - 4], ".str" ) &&
200             strcasecmp( &p_demux->psz_file[i_len - 4], ".xai" ) &&
201             strcasecmp( &p_demux->psz_file[i_len - 3], ".xa" ) )
202         {
203             free( psz_url );
204             return VLC_EGENERIC;
205         }
206     }
207
208     msg_Dbg( p_demux, "detected format: %s", fmt->name );
209
210     /* Fill p_demux fields */
211     p_demux->pf_demux = Demux;
212     p_demux->pf_control = Control;
213     p_demux->p_sys = p_sys = malloc( sizeof( demux_sys_t ) );
214     p_sys->ic = 0;
215     p_sys->fmt = fmt;
216     p_sys->i_tk = 0;
217     p_sys->tk = NULL;
218     p_sys->tk_pcr = NULL;
219     p_sys->i_ssa_order = 0;
220     TAB_INIT( p_sys->i_attachments, p_sys->attachments);
221     p_sys->p_title = NULL;
222
223     /* Create I/O wrapper */
224     p_sys->io_buffer_size = 32768;  /* FIXME */
225     p_sys->io_buffer = malloc( p_sys->io_buffer_size );
226
227 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(2<<8)+0)
228     p_sys->ic = avformat_alloc_context();
229     p_sys->ic->pb = avio_alloc_context( p_sys->io_buffer,
230         p_sys->io_buffer_size, 0, p_demux, IORead, NULL, IOSeek );
231     p_sys->ic->pb->seekable = b_can_seek ? AVIO_SEEKABLE_NORMAL : 0;
232     error = avformat_open_input(&p_sys->ic, psz_url, p_sys->fmt, NULL);
233 #else
234     init_put_byte( &p_sys->io, p_sys->io_buffer, p_sys->io_buffer_size, 0,
235         p_demux, IORead, NULL, IOSeek );
236     p_sys->io.is_streamed = !b_can_seek;
237 # if defined(AVIO_SEEKABLE_NORMAL)
238     p_sys->io.seekable = !!b_can_seek;
239 # endif
240     error = av_open_input_stream(&p_sys->ic, &p_sys->io, psz_url, p_sys->fmt, NULL);
241 #endif
242
243     free( psz_url );
244     if( error < 0 )
245     {
246         errno = AVUNERROR(error);
247         msg_Err( p_demux, "Could not open %s: %m", psz_url );
248         p_sys->ic = NULL;
249         CloseDemux( p_this );
250         return VLC_EGENERIC;
251     }
252
253 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(26<<8)+0)
254     char *psz_opts = var_InheritString( p_demux, "avformat-options" );
255     AVDictionary *options[p_sys->ic->nb_streams ? p_sys->ic->nb_streams : 1];
256     options[0] = NULL;
257     for (unsigned i = 1; i < p_sys->ic->nb_streams; i++)
258         options[i] = NULL;
259     if (psz_opts && *psz_opts) {
260         options[0] = vlc_av_get_options(psz_opts);
261         for (unsigned i = 1; i < p_sys->ic->nb_streams; i++) {
262             av_dict_copy(&options[i], options[0], 0);
263         }
264     }
265     free(psz_opts);
266     vlc_avcodec_lock(); /* avformat calls avcodec behind our back!!! */
267     error = avformat_find_stream_info( p_sys->ic, options );
268     vlc_avcodec_unlock();
269     AVDictionaryEntry *t = NULL;
270     while ((t = av_dict_get(options[0], "", t, AV_DICT_IGNORE_SUFFIX))) {
271         msg_Err( p_demux, "Unknown option \"%s\"", t->key );
272     }
273     av_dict_free(&options[0]);
274     for (unsigned i = 1; i < p_sys->ic->nb_streams; i++) {
275         av_dict_free(&options[i]);
276     }
277 #else
278     vlc_avcodec_lock(); /* avformat calls avcodec behind our back!!! */
279     error = av_find_stream_info( p_sys->ic );
280     vlc_avcodec_unlock();
281 #endif
282
283     if( error < 0 )
284     {
285         errno = AVUNERROR(error);
286         msg_Warn( p_demux, "Could not find stream info: %m" );
287     }
288
289     for( i = 0; i < p_sys->ic->nb_streams; i++ )
290     {
291         AVStream *s = p_sys->ic->streams[i];
292         AVCodecContext *cc = s->codec;
293
294         es_out_id_t  *es;
295         es_format_t  fmt;
296         vlc_fourcc_t fcc;
297         const char *psz_type = "unknown";
298
299         if( !GetVlcFourcc( cc->codec_id, NULL, &fcc, NULL ) )
300             fcc = VLC_FOURCC( 'u', 'n', 'd', 'f' );
301
302         switch( cc->codec_type )
303         {
304         case AVMEDIA_TYPE_AUDIO:
305             es_format_Init( &fmt, AUDIO_ES, fcc );
306             fmt.i_bitrate = cc->bit_rate;
307             fmt.audio.i_channels = cc->channels;
308             fmt.audio.i_rate = cc->sample_rate;
309             fmt.audio.i_bitspersample = cc->bits_per_coded_sample;
310             fmt.audio.i_blockalign = cc->block_align;
311             psz_type = "audio";
312             break;
313
314         case AVMEDIA_TYPE_VIDEO:
315             es_format_Init( &fmt, VIDEO_ES, fcc );
316
317             /* Special case for raw video data */
318             if( cc->codec_id == CODEC_ID_RAWVIDEO )
319             {
320                 msg_Dbg( p_demux, "raw video, pixel format: %i", cc->pix_fmt );
321                 if( GetVlcChroma( &fmt.video, cc->pix_fmt ) != VLC_SUCCESS)
322                 {
323                     msg_Err( p_demux, "was unable to find a FourCC match for raw video" );
324                 }
325                 else
326                     fmt.i_codec = fmt.video.i_chroma;
327             }
328             /* We need this for the h264 packetizer */
329             else if( cc->codec_id == CODEC_ID_H264 && ( p_sys->fmt == av_find_input_format("flv") ||
330                 p_sys->fmt == av_find_input_format("matroska") || p_sys->fmt == av_find_input_format("mp4") ) )
331                 fmt.i_original_fourcc = VLC_FOURCC( 'a', 'v', 'c', '1' );
332
333             fmt.video.i_width = cc->width;
334             fmt.video.i_height = cc->height;
335 #if LIBAVCODEC_VERSION_MAJOR < 54
336             if( cc->palctrl )
337             {
338                 fmt.video.p_palette = malloc( sizeof(video_palette_t) );
339                 *fmt.video.p_palette = *(video_palette_t *)cc->palctrl;
340             }
341 #else
342 # warning FIXME: implement palette transmission
343 #endif
344             psz_type = "video";
345             fmt.video.i_frame_rate = cc->time_base.den;
346             fmt.video.i_frame_rate_base = cc->time_base.num * __MAX( cc->ticks_per_frame, 1 );
347             break;
348
349         case AVMEDIA_TYPE_SUBTITLE:
350             es_format_Init( &fmt, SPU_ES, fcc );
351             if( strncmp( p_sys->ic->iformat->name, "matroska", 8 ) == 0 &&
352                 cc->codec_id == CODEC_ID_DVD_SUBTITLE &&
353                 cc->extradata != NULL &&
354                 cc->extradata_size > 0 )
355             {
356                 char *psz_start;
357                 char *psz_buf = malloc( cc->extradata_size + 1);
358                 if( psz_buf != NULL )
359                 {
360                     memcpy( psz_buf, cc->extradata , cc->extradata_size );
361                     psz_buf[cc->extradata_size] = '\0';
362
363                     psz_start = strstr( psz_buf, "size:" );
364                     if( psz_start &&
365                         vobsub_size_parse( psz_start,
366                                            &fmt.subs.spu.i_original_frame_width,
367                                            &fmt.subs.spu.i_original_frame_height ) == VLC_SUCCESS )
368                     {
369                         msg_Dbg( p_demux, "original frame size: %dx%d",
370                                  fmt.subs.spu.i_original_frame_width,
371                                  fmt.subs.spu.i_original_frame_height );
372                     }
373                     else
374                     {
375                         msg_Warn( p_demux, "reading original frame size failed" );
376                     }
377
378                     psz_start = strstr( psz_buf, "palette:" );
379                     if( psz_start &&
380                         vobsub_palette_parse( psz_start, &fmt.subs.spu.palette[1] ) == VLC_SUCCESS )
381                     {
382                         fmt.subs.spu.palette[0] =  0xBeef;
383                         msg_Dbg( p_demux, "vobsub palette read" );
384                     }
385                     else
386                     {
387                         msg_Warn( p_demux, "reading original palette failed" );
388                     }
389                     free( psz_buf );
390                 }
391             }
392
393             psz_type = "subtitle";
394             break;
395
396         default:
397             es_format_Init( &fmt, UNKNOWN_ES, 0 );
398 #ifdef HAVE_AVUTIL_CODEC_ATTACHMENT
399             if( cc->codec_type == AVMEDIA_TYPE_ATTACHMENT )
400             {
401                 input_attachment_t *p_attachment;
402
403                 psz_type = "attachment";
404                 if( cc->codec_id == CODEC_ID_TTF )
405                 {
406                     AVDictionaryEntry *filename = av_dict_get( s->metadata, "filename", NULL, 0 );
407                     if( filename && filename->value )
408                     {
409                         p_attachment = vlc_input_attachment_New(
410                                 filename->value, "application/x-truetype-font",
411                                 NULL, cc->extradata, (int)cc->extradata_size );
412                         TAB_APPEND( p_sys->i_attachments, p_sys->attachments,
413                                 p_attachment );
414                     }
415                 }
416                 else msg_Warn( p_demux, "unsupported attachment type (%u) in avformat demux", cc->codec_id );
417             }
418             else
419 #endif
420             {
421                 if( cc->codec_type == AVMEDIA_TYPE_DATA )
422                     psz_type = "data";
423
424                 msg_Warn( p_demux, "unsupported track type (%u:%u) in avformat demux", cc->codec_type, cc->codec_id );
425             }
426             break;
427         }
428
429         AVDictionaryEntry *language = av_dict_get( s->metadata, "language", NULL, 0 );
430         if ( language && language->value )
431             fmt.psz_language = strdup( language->value );
432
433         if( s->disposition & AV_DISPOSITION_DEFAULT )
434             fmt.i_priority = 1000;
435
436 #ifdef HAVE_AVUTIL_CODEC_ATTACHMENT
437         if( cc->codec_type != AVMEDIA_TYPE_ATTACHMENT )
438 #endif
439         if( cc->codec_type != AVMEDIA_TYPE_DATA )
440         {
441             const bool    b_ogg = !strcmp( p_sys->fmt->name, "ogg" );
442             const uint8_t *p_extra = cc->extradata;
443             unsigned      i_extra  = cc->extradata_size;
444
445             if( cc->codec_id == CODEC_ID_THEORA && b_ogg )
446             {
447                 unsigned pi_size[3];
448                 const void *pp_data[3];
449                 unsigned i_count;
450                 for( i_count = 0; i_count < 3; i_count++ )
451                 {
452                     if( i_extra < 2 )
453                         break;
454                     pi_size[i_count] = GetWBE( p_extra );
455                     pp_data[i_count] = &p_extra[2];
456                     if( i_extra < pi_size[i_count] + 2 )
457                         break;
458
459                     p_extra += 2 + pi_size[i_count];
460                     i_extra -= 2 + pi_size[i_count];
461                 }
462                 if( i_count > 0 && xiph_PackHeaders( &fmt.i_extra, &fmt.p_extra,
463                                                      pi_size, pp_data, i_count ) )
464                 {
465                     fmt.i_extra = 0;
466                     fmt.p_extra = NULL;
467                 }
468             }
469             else if( cc->codec_id == CODEC_ID_SPEEX && b_ogg )
470             {
471                 const uint8_t p_dummy_comment[] = {
472                     0, 0, 0, 0,
473                     0, 0, 0, 0,
474                 };
475                 unsigned pi_size[2];
476                 const void *pp_data[2];
477
478                 pi_size[0] = i_extra;
479                 pp_data[0] = p_extra;
480
481                 pi_size[1] = sizeof(p_dummy_comment);
482                 pp_data[1] = p_dummy_comment;
483
484                 if( pi_size[0] > 0 && xiph_PackHeaders( &fmt.i_extra, &fmt.p_extra,
485                                                         pi_size, pp_data, 2 ) )
486                 {
487                     fmt.i_extra = 0;
488                     fmt.p_extra = NULL;
489                 }
490             }
491             else if( cc->extradata_size > 0 )
492             {
493                 fmt.p_extra = malloc( i_extra );
494                 if( fmt.p_extra )
495                 {
496                     fmt.i_extra = i_extra;
497                     memcpy( fmt.p_extra, p_extra, i_extra );
498                 }
499             }
500             es = es_out_Add( p_demux->out, &fmt );
501             if( s->disposition & AV_DISPOSITION_DEFAULT )
502                 es_out_Control( p_demux->out, ES_OUT_SET_ES_DEFAULT, es );
503             es_format_Clean( &fmt );
504
505             msg_Dbg( p_demux, "adding es: %s codec = %4.4s",
506                      psz_type, (char*)&fcc );
507             TAB_APPEND( p_sys->i_tk, p_sys->tk, es );
508         }
509     }
510     p_sys->tk_pcr = calloc( p_sys->i_tk, sizeof(*p_sys->tk_pcr) );
511
512     if( p_sys->ic->start_time != (int64_t)AV_NOPTS_VALUE )
513         i_start_time = p_sys->ic->start_time * 1000000 / AV_TIME_BASE;
514
515     msg_Dbg( p_demux, "AVFormat supported stream" );
516     msg_Dbg( p_demux, "    - format = %s (%s)",
517              p_sys->fmt->name, p_sys->fmt->long_name );
518     msg_Dbg( p_demux, "    - start time = %"PRId64, i_start_time );
519     msg_Dbg( p_demux, "    - duration = %"PRId64,
520              ( p_sys->ic->duration != (int64_t)AV_NOPTS_VALUE ) ?
521              p_sys->ic->duration * 1000000 / AV_TIME_BASE : -1 );
522
523     if( p_sys->ic->nb_chapters > 0 )
524     {
525         p_sys->p_title = vlc_input_title_New();
526         p_sys->p_title->i_length = p_sys->ic->duration * 1000000 / AV_TIME_BASE;
527     }
528
529     for( i = 0; i < p_sys->ic->nb_chapters; i++ )
530     {
531         seekpoint_t *s = vlc_seekpoint_New();
532
533         AVDictionaryEntry *title = av_dict_get( p_sys->ic->metadata, "title", NULL, 0);
534         if( title && title->value )
535         {
536             s->psz_name = strdup( title->value );
537             EnsureUTF8( s->psz_name );
538             msg_Dbg( p_demux, "    - chapter %d: %s", i, s->psz_name );
539         }
540         s->i_time_offset = p_sys->ic->chapters[i]->start * 1000000 *
541             p_sys->ic->chapters[i]->time_base.num /
542             p_sys->ic->chapters[i]->time_base.den -
543             (i_start_time != -1 ? i_start_time : 0 );
544         TAB_APPEND( p_sys->p_title->i_seekpoint, p_sys->p_title->seekpoint, s );
545     }
546
547     ResetTime( p_demux, 0 );
548     return VLC_SUCCESS;
549 }
550
551 /*****************************************************************************
552  * Close
553  *****************************************************************************/
554 void CloseDemux( vlc_object_t *p_this )
555 {
556     demux_t     *p_demux = (demux_t*)p_this;
557     demux_sys_t *p_sys = p_demux->p_sys;
558
559     FREENULL( p_sys->tk );
560     free( p_sys->tk_pcr );
561
562     if( p_sys->ic )
563     {
564 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(2<<8)+0)
565         av_free( p_sys->ic->pb );
566 #endif
567 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(26<<8)+0)
568         avformat_close_input( &p_sys->ic );
569 #else
570         av_close_input_stream( p_sys->ic );
571 #endif
572     }
573
574     for( int i = 0; i < p_sys->i_attachments; i++ )
575         free( p_sys->attachments[i] );
576     TAB_CLEAN( p_sys->i_attachments, p_sys->attachments);
577
578     if( p_sys->p_title )
579         vlc_input_title_Delete( p_sys->p_title );
580
581     free( p_sys->io_buffer );
582     free( p_sys );
583 }
584
585 /*****************************************************************************
586  * Demux:
587  *****************************************************************************/
588 static int Demux( demux_t *p_demux )
589 {
590     demux_sys_t *p_sys = p_demux->p_sys;
591     AVPacket    pkt;
592     block_t     *p_frame;
593     int64_t     i_start_time;
594
595     /* Read a frame */
596     int i_av_ret = av_read_frame( p_sys->ic, &pkt );
597     if( i_av_ret )
598     {
599         /* Avoid EOF if av_read_frame returns AVERROR(EAGAIN) */
600         if( i_av_ret == AVERROR(EAGAIN) )
601             return 1;
602
603         return 0;
604     }
605     if( pkt.stream_index < 0 || pkt.stream_index >= p_sys->i_tk )
606     {
607         av_free_packet( &pkt );
608         return 1;
609     }
610     const AVStream *p_stream = p_sys->ic->streams[pkt.stream_index];
611     if( p_stream->time_base.den <= 0 )
612     {
613         msg_Warn( p_demux, "Invalid time base for the stream %d", pkt.stream_index );
614         av_free_packet( &pkt );
615         return 1;
616     }
617     if( p_stream->codec->codec_id == CODEC_ID_SSA )
618     {
619         p_frame = BuildSsaFrame( &pkt, p_sys->i_ssa_order++ );
620         if( !p_frame )
621         {
622             av_free_packet( &pkt );
623             return 1;
624         }
625     }
626     else
627     {
628         if( ( p_frame = block_New( p_demux, pkt.size ) ) == NULL )
629         {
630             av_free_packet( &pkt );
631             return 0;
632         }
633         memcpy( p_frame->p_buffer, pkt.data, pkt.size );
634     }
635
636     if( pkt.flags & AV_PKT_FLAG_KEY )
637         p_frame->i_flags |= BLOCK_FLAG_TYPE_I;
638
639     /* Used to avoid timestamps overlow */
640     lldiv_t q;
641     if( p_sys->ic->start_time != (int64_t)AV_NOPTS_VALUE )
642     {
643         q = lldiv( p_sys->ic->start_time, AV_TIME_BASE);
644         i_start_time = q.quot * (int64_t)1000000 + q.rem * (int64_t)1000000 / AV_TIME_BASE;
645     }
646     else
647         i_start_time = 0;
648
649     if( pkt.dts == (int64_t)AV_NOPTS_VALUE )
650         p_frame->i_dts = VLC_TS_INVALID;
651     else
652     {
653         q = lldiv( pkt.dts, p_stream->time_base.den );
654         p_frame->i_dts = q.quot * (int64_t)1000000 *
655             p_stream->time_base.num + q.rem * (int64_t)1000000 *
656             p_stream->time_base.num /
657             p_stream->time_base.den - i_start_time + VLC_TS_0;
658     }
659
660     if( pkt.pts == (int64_t)AV_NOPTS_VALUE )
661         p_frame->i_pts = VLC_TS_INVALID;
662     else
663     {
664         q = lldiv( pkt.pts, p_stream->time_base.den );
665         p_frame->i_pts = q.quot * (int64_t)1000000 *
666             p_stream->time_base.num + q.rem * (int64_t)1000000 *
667             p_stream->time_base.num /
668             p_stream->time_base.den - i_start_time + VLC_TS_0;
669     }
670     if( pkt.duration > 0 && p_frame->i_length <= 0 )
671         p_frame->i_length = pkt.duration * 1000000 *
672             p_stream->time_base.num /
673             p_stream->time_base.den;
674
675     if( pkt.dts != (int64_t)AV_NOPTS_VALUE && pkt.dts == pkt.pts &&
676         p_stream->codec->codec_type == AVMEDIA_TYPE_VIDEO )
677     {
678         /* Add here notoriously bugged file formats/samples regarding PTS */
679         if( !strcmp( p_sys->fmt->name, "flv" ) )
680             p_frame->i_pts = VLC_TS_INVALID;
681     }
682 #ifdef AVFORMAT_DEBUG
683     msg_Dbg( p_demux, "tk[%d] dts=%"PRId64" pts=%"PRId64,
684              pkt.stream_index, p_frame->i_dts, p_frame->i_pts );
685 #endif
686     if( p_frame->i_dts > VLC_TS_INVALID )
687         p_sys->tk_pcr[pkt.stream_index] = p_frame->i_dts;
688
689     int64_t i_ts_max = INT64_MIN;
690     for( int i = 0; i < p_sys->i_tk; i++ )
691         i_ts_max = __MAX( i_ts_max, p_sys->tk_pcr[i] );
692
693     int64_t i_ts_min = INT64_MAX;
694     for( int i = 0; i < p_sys->i_tk; i++ )
695     {
696         if( p_sys->tk_pcr[i] > VLC_TS_INVALID && p_sys->tk_pcr[i] + 10 * CLOCK_FREQ >= i_ts_max )
697             i_ts_min = __MIN( i_ts_min, p_sys->tk_pcr[i] );
698     }
699     if( i_ts_min >= p_sys->i_pcr )
700     {
701         p_sys->i_pcr = i_ts_min;
702         es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pcr );
703         UpdateSeekPoint( p_demux, p_sys->i_pcr );
704     }
705
706     es_out_Send( p_demux->out, p_sys->tk[pkt.stream_index], p_frame );
707
708     av_free_packet( &pkt );
709     return 1;
710 }
711
712 static void UpdateSeekPoint( demux_t *p_demux, int64_t i_time )
713 {
714     demux_sys_t *p_sys = p_demux->p_sys;
715     int i;
716
717     if( !p_sys->p_title )
718         return;
719
720     for( i = 0; i < p_sys->p_title->i_seekpoint; i++ )
721     {
722         if( i_time < p_sys->p_title->seekpoint[i]->i_time_offset )
723             break;
724     }
725     i--;
726
727     if( i != p_demux->info.i_seekpoint && i >= 0 )
728     {
729         p_demux->info.i_seekpoint = i;
730         p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
731     }
732 }
733
734 static void ResetTime( demux_t *p_demux, int64_t i_time )
735 {
736     demux_sys_t *p_sys = p_demux->p_sys;
737
738     if( p_sys->ic->start_time == (int64_t)AV_NOPTS_VALUE || i_time < 0 )
739         i_time = VLC_TS_INVALID;
740     else if( i_time == 0 )
741         i_time = 1;
742
743     p_sys->i_pcr = i_time;
744     for( int i = 0; i < p_sys->i_tk; i++ )
745         p_sys->tk_pcr[i] = i_time;
746
747     if( i_time > VLC_TS_INVALID )
748     {
749         es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, i_time );
750         UpdateSeekPoint( p_demux, i_time );
751     }
752 }
753
754 static block_t *BuildSsaFrame( const AVPacket *p_pkt, unsigned i_order )
755 {
756     if( p_pkt->size <= 0 )
757         return NULL;
758
759     char buffer[256];
760     const size_t i_buffer_size = __MIN( (int)sizeof(buffer) - 1, p_pkt->size );
761     memcpy( buffer, p_pkt->data, i_buffer_size );
762     buffer[i_buffer_size] = '\0';
763
764     /* */
765     int i_layer;
766     int h0, m0, s0, c0;
767     int h1, m1, s1, c1;
768     int i_position = 0;
769     if( sscanf( buffer, "Dialogue: %d,%d:%d:%d.%d,%d:%d:%d.%d,%n", &i_layer,
770                 &h0, &m0, &s0, &c0, &h1, &m1, &s1, &c1, &i_position ) < 9 )
771         return NULL;
772     if( i_position <= 0 || (unsigned)i_position >= i_buffer_size )
773         return NULL;
774
775     char *p;
776     if( asprintf( &p, "%u,%d,%.*s", i_order, i_layer, p_pkt->size - i_position, p_pkt->data + i_position ) < 0 )
777         return NULL;
778
779     block_t *p_frame = block_heap_Alloc( p, strlen(p) + 1 );
780     if( p_frame )
781         p_frame->i_length = CLOCK_FREQ * ((h1-h0) * 3600 +
782                                           (m1-m0) * 60 +
783                                           (s1-s0) * 1) +
784                             CLOCK_FREQ * (c1-c0) / 100;
785     return p_frame;
786 }
787
788 /*****************************************************************************
789  * Control:
790  *****************************************************************************/
791 static int Control( demux_t *p_demux, int i_query, va_list args )
792 {
793     demux_sys_t *p_sys = p_demux->p_sys;
794     const int64_t i_start_time = p_sys->ic->start_time != (int64_t)AV_NOPTS_VALUE ? p_sys->ic->start_time : 0;
795     double f, *pf;
796     int64_t i64, *pi64;
797
798     switch( i_query )
799     {
800         case DEMUX_GET_POSITION:
801             pf = (double*) va_arg( args, double* ); *pf = 0.0;
802             i64 = stream_Size( p_demux->s );
803             if( i64 > 0 )
804             {
805                 double current = stream_Tell( p_demux->s );
806                 *pf = current / (double)i64;
807             }
808
809             if( (p_sys->ic->duration != (int64_t)AV_NOPTS_VALUE) && (p_sys->i_pcr > 0) )
810             {
811                 *pf = (double)p_sys->i_pcr / (double)p_sys->ic->duration;
812             }
813
814             return VLC_SUCCESS;
815
816         case DEMUX_SET_POSITION:
817             f = (double) va_arg( args, double );
818             i64 = p_sys->ic->duration * f + i_start_time;
819
820             msg_Warn( p_demux, "DEMUX_SET_POSITION: %"PRId64, i64 );
821
822             /* If we have a duration, we prefer to seek by time
823                but if we don't, or if the seek fails, try BYTE seeking */
824             if( p_sys->ic->duration == (int64_t)AV_NOPTS_VALUE ||
825                 (av_seek_frame( p_sys->ic, -1, i64, AVSEEK_FLAG_BACKWARD ) < 0) )
826             {
827                 int64_t i_size = stream_Size( p_demux->s );
828                 i64 = (i_size * f);
829
830                 msg_Warn( p_demux, "DEMUX_SET_BYTE_POSITION: %"PRId64, i64 );
831                 if( av_seek_frame( p_sys->ic, -1, i64, AVSEEK_FLAG_BYTE ) < 0 )
832                     return VLC_EGENERIC;
833
834                 ResetTime( p_demux, -1 );
835             }
836             else
837             {
838                 ResetTime( p_demux, i64 - i_start_time );
839             }
840             return VLC_SUCCESS;
841
842         case DEMUX_GET_LENGTH:
843             pi64 = (int64_t*)va_arg( args, int64_t * );
844             if( p_sys->ic->duration != (int64_t)AV_NOPTS_VALUE )
845                 *pi64 = p_sys->ic->duration * 1000000 / AV_TIME_BASE;
846             else
847                 *pi64 = 0;
848             return VLC_SUCCESS;
849
850         case DEMUX_GET_TIME:
851             pi64 = (int64_t*)va_arg( args, int64_t * );
852             *pi64 = p_sys->i_pcr;
853             return VLC_SUCCESS;
854
855         case DEMUX_SET_TIME:
856         {
857             i64 = (int64_t)va_arg( args, int64_t );
858             i64 = i64 *AV_TIME_BASE / 1000000 + i_start_time;
859
860             msg_Warn( p_demux, "DEMUX_SET_TIME: %"PRId64, i64 );
861
862             if( av_seek_frame( p_sys->ic, -1, i64, AVSEEK_FLAG_BACKWARD ) < 0 )
863             {
864                 return VLC_EGENERIC;
865             }
866             ResetTime( p_demux, i64 - i_start_time );
867             return VLC_SUCCESS;
868         }
869
870         case DEMUX_HAS_UNSUPPORTED_META:
871         {
872             bool *pb_bool = (bool*)va_arg( args, bool* );
873             *pb_bool = true;
874             return VLC_SUCCESS;
875         }
876
877
878         case DEMUX_GET_META:
879         {
880             vlc_meta_t *p_meta = (vlc_meta_t*)va_arg( args, vlc_meta_t* );
881
882             AVDictionaryEntry *title = av_dict_get( p_sys->ic->metadata, "language", NULL, 0 );
883             AVDictionaryEntry *artist = av_dict_get( p_sys->ic->metadata, "artist", NULL, 0 );
884             AVDictionaryEntry *copyright = av_dict_get( p_sys->ic->metadata, "copyright", NULL, 0 );
885             AVDictionaryEntry *comment = av_dict_get( p_sys->ic->metadata, "comment", NULL, 0 );
886             AVDictionaryEntry *genre = av_dict_get( p_sys->ic->metadata, "genre", NULL, 0 );
887
888             if( title && title->value )
889                 vlc_meta_SetTitle( p_meta, title->value );
890             if( artist && artist->value )
891                 vlc_meta_SetArtist( p_meta, artist->value );
892             if( copyright && copyright->value )
893                 vlc_meta_SetCopyright( p_meta, copyright->value );
894             if( comment && comment->value )
895                 vlc_meta_SetDescription( p_meta, comment->value );
896             if( genre && genre->value )
897                 vlc_meta_SetGenre( p_meta, genre->value );
898             return VLC_SUCCESS;
899         }
900
901         case DEMUX_GET_ATTACHMENTS:
902         {
903             input_attachment_t ***ppp_attach =
904                 (input_attachment_t***)va_arg( args, input_attachment_t*** );
905             int *pi_int = (int*)va_arg( args, int * );
906             int i;
907
908             if( p_sys->i_attachments <= 0 )
909                 return VLC_EGENERIC;
910
911             *pi_int = p_sys->i_attachments;;
912             *ppp_attach = malloc( sizeof(input_attachment_t**) * p_sys->i_attachments );
913             for( i = 0; i < p_sys->i_attachments; i++ )
914                 (*ppp_attach)[i] = vlc_input_attachment_Duplicate( p_sys->attachments[i] );
915             return VLC_SUCCESS;
916         }
917
918         case DEMUX_GET_TITLE_INFO:
919         {
920             input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
921             int *pi_int    = (int*)va_arg( args, int* );
922             int *pi_title_offset = (int*)va_arg( args, int* );
923             int *pi_seekpoint_offset = (int*)va_arg( args, int* );
924
925             if( !p_sys->p_title )
926                 return VLC_EGENERIC;
927
928             *pi_int = 1;
929             *ppp_title = malloc( sizeof( input_title_t**) );
930             (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->p_title );
931             *pi_title_offset = 0;
932             *pi_seekpoint_offset = 0;
933             return VLC_SUCCESS;
934         }
935         case DEMUX_SET_TITLE:
936         {
937             const int i_title = (int)va_arg( args, int );
938             if( !p_sys->p_title || i_title != 0 )
939                 return VLC_EGENERIC;
940             return VLC_SUCCESS;
941         }
942         case DEMUX_SET_SEEKPOINT:
943         {
944             const int i_seekpoint = (int)va_arg( args, int );
945             if( !p_sys->p_title )
946                 return VLC_EGENERIC;
947
948             i64 = p_sys->p_title->seekpoint[i_seekpoint]->i_time_offset *
949                   AV_TIME_BASE / 1000000 + i_start_time;
950
951             msg_Warn( p_demux, "DEMUX_SET_TIME: %"PRId64, i64 );
952
953             if( av_seek_frame( p_sys->ic, -1, i64, AVSEEK_FLAG_BACKWARD ) < 0 )
954             {
955                 return VLC_EGENERIC;
956             }
957             ResetTime( p_demux, i64 - i_start_time );
958             return VLC_SUCCESS;
959         }
960
961
962         default:
963             return VLC_EGENERIC;
964     }
965 }
966
967 /*****************************************************************************
968  * I/O wrappers for libavformat
969  *****************************************************************************/
970 static int IORead( void *opaque, uint8_t *buf, int buf_size )
971 {
972     demux_t *p_demux = opaque;
973     if( buf_size < 0 ) return -1;
974     int i_ret = stream_Read( p_demux->s, buf, buf_size );
975     return i_ret ? i_ret : -1;
976 }
977
978 static int64_t IOSeek( void *opaque, int64_t offset, int whence )
979 {
980     demux_t *p_demux = opaque;
981     int64_t i_absolute;
982     int64_t i_size = stream_Size( p_demux->s );
983
984 #ifdef AVFORMAT_DEBUG
985     msg_Warn( p_demux, "IOSeek offset: %"PRId64", whence: %i", offset, whence );
986 #endif
987
988     switch( whence )
989     {
990 #ifdef AVSEEK_SIZE
991         case AVSEEK_SIZE:
992             return i_size;
993 #endif
994         case SEEK_SET:
995             i_absolute = (int64_t)offset;
996             break;
997         case SEEK_CUR:
998             i_absolute = stream_Tell( p_demux->s ) + (int64_t)offset;
999             break;
1000         case SEEK_END:
1001             i_absolute = i_size + (int64_t)offset;
1002             break;
1003         default:
1004             return -1;
1005
1006     }
1007
1008     if( i_absolute < 0 )
1009     {
1010         msg_Dbg( p_demux, "Trying to seek before the beginning" );
1011         return -1;
1012     }
1013
1014     if( i_size > 0 && i_absolute >= i_size )
1015     {
1016         msg_Dbg( p_demux, "Trying to seek too far : EOF?" );
1017         return -1;
1018     }
1019
1020     if( stream_Seek( p_demux->s, i_absolute ) )
1021     {
1022         msg_Warn( p_demux, "we were not allowed to seek, or EOF " );
1023         return -1;
1024     }
1025
1026     return stream_Tell( p_demux->s );
1027 }
1028
1029 #endif /* HAVE_LIBAVFORMAT_AVFORMAT_H */