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