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