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