coreaudio: fix invalid delay after a unpause
[vlc.git] / modules / demux / avformat / demux.c
1 /*****************************************************************************
2  * demux.c: demuxer using libavformat
3  *****************************************************************************
4  * Copyright (C) 2004-2009 VLC authors and VideoLAN
5  *
6  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
7  *          Gildas Bazin <gbazin@videolan.org>
8  *
9  * This program is free software; you can redistribute it and/or modify it
10  * under the terms of the GNU Lesser General Public License as published by
11  * the Free Software Foundation; either version 2.1 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <vlc_common.h>
33 #include <vlc_demux.h>
34 #include <vlc_stream.h>
35 #include <vlc_meta.h>
36 #include <vlc_input.h>
37 #include <vlc_charset.h>
38 #include <vlc_avcodec.h>
39
40 #include "../../codec/avcodec/avcodec.h"
41 #include "../../codec/avcodec/chroma.h"
42 #include "../../codec/avcodec/avcommon_compat.h"
43 #include "avformat.h"
44 #include "../xiph.h"
45 #include "../vobsub.h"
46
47 #include <libavformat/avformat.h>
48 #include <libavutil/display.h>
49
50 //#define AVFORMAT_DEBUG 1
51
52 # define HAVE_AVUTIL_CODEC_ATTACHMENT 1
53
54 struct avformat_track_s
55 {
56     es_out_id_t *p_es;
57     vlc_tick_t i_pcr;
58 };
59
60 /*****************************************************************************
61  * demux_sys_t: demux descriptor
62  *****************************************************************************/
63 typedef struct
64 {
65     AVInputFormat  *fmt;
66     AVFormatContext *ic;
67
68     struct avformat_track_s *tracks;
69     unsigned i_tracks;
70
71     vlc_tick_t      i_pcr;
72
73     unsigned    i_ssa_order;
74
75     int                i_attachments;
76     input_attachment_t **attachments;
77
78     /* Only one title with seekpoints possible atm. */
79     input_title_t *p_title;
80     int i_seekpoint;
81     unsigned i_update;
82 } demux_sys_t;
83
84 #define AVFORMAT_IOBUFFER_SIZE 32768  /* FIXME */
85
86 /*****************************************************************************
87  * Local prototypes
88  *****************************************************************************/
89 static int Demux  ( demux_t *p_demux );
90 static int Control( demux_t *p_demux, int i_query, va_list args );
91
92 static int IORead( void *opaque, uint8_t *buf, int buf_size );
93 static int64_t IOSeek( void *opaque, int64_t offset, int whence );
94
95 static block_t *BuildSsaFrame( const AVPacket *p_pkt, unsigned i_order );
96 static void UpdateSeekPoint( demux_t *p_demux, vlc_tick_t i_time );
97 static void ResetTime( demux_t *p_demux, int64_t i_time );
98
99 static vlc_fourcc_t CodecTagToFourcc( uint32_t codec_tag )
100 {
101     // convert from little-endian avcodec codec_tag to VLC native-endian fourcc
102 #ifdef WORDS_BIGENDIAN
103     return vlc_bswap32(codec_tag);
104 #else
105     return codec_tag;
106 #endif
107 }
108
109 /*****************************************************************************
110  * Open
111  *****************************************************************************/
112
113 static void get_rotation(es_format_t *fmt, AVStream *s)
114 {
115     char const *kRotateKey = "rotate";
116     AVDictionaryEntry *rotation = av_dict_get(s->metadata, kRotateKey, NULL, 0);
117     long angle = 0;
118
119     int32_t *matrix = (int32_t *)av_stream_get_side_data(s, AV_PKT_DATA_DISPLAYMATRIX, NULL);
120     if( matrix ) {
121         int64_t det = (int64_t)matrix[0] * matrix[4] - (int64_t)matrix[1] * matrix[3];
122         if (det < 0) {
123             /* Flip the matrix to decouple flip and rotation operations.
124              * Always assume an horizontal flip for simplicity,
125              * it can be changed later if rotation is 180º. */
126             av_display_matrix_flip(matrix, 1, 0);
127         }
128         angle = lround(av_display_rotation_get(matrix));
129
130         if (angle > 45 && angle < 135)
131             fmt->video.orientation = ORIENT_ROTATED_270;
132
133         else if (angle > 135 || angle < -135) {
134             if (det < 0)
135                 fmt->video.orientation = ORIENT_VFLIPPED;
136             else
137                 fmt->video.orientation = ORIENT_ROTATED_180;
138         }
139         else if (angle < -45 && angle > -135)
140             fmt->video.orientation = ORIENT_ROTATED_90;
141
142         else
143             fmt->video.orientation = ORIENT_NORMAL;
144
145         /* Flip is already applied to the 180º case. */
146         if (det < 0 && !(angle > 135 || angle < -135)) {
147             video_transform_t transform = (video_transform_t)fmt->video.orientation;
148             /* Flip first then rotate */
149             fmt->video.orientation = ORIENT_HFLIPPED;
150             video_format_TransformBy(&fmt->video, transform);
151         }
152
153     } else if( rotation ) {
154         angle = strtol(rotation->value, NULL, 10);
155
156         if (angle > 45 && angle < 135)
157             fmt->video.orientation = ORIENT_ROTATED_90;
158
159         else if (angle > 135 && angle < 225)
160             fmt->video.orientation = ORIENT_ROTATED_180;
161
162         else if (angle > 225 && angle < 315)
163             fmt->video.orientation = ORIENT_ROTATED_270;
164
165         else
166             fmt->video.orientation = ORIENT_NORMAL;
167     }
168 }
169
170 static AVDictionary * BuildAVOptions( demux_t *p_demux )
171 {
172     char *psz_opts = var_InheritString( p_demux, "avformat-options" );
173     AVDictionary *options = NULL;
174     if( psz_opts )
175     {
176         vlc_av_get_options( psz_opts, &options );
177         free( psz_opts );
178     }
179     return options;
180 }
181
182 static void FreeUnclaimedOptions( demux_t *p_demux, AVDictionary **pp_dict )
183 {
184     AVDictionaryEntry *t = NULL;
185     while ((t = av_dict_get(*pp_dict, "", t, AV_DICT_IGNORE_SUFFIX))) {
186         msg_Err( p_demux, "Unknown option \"%s\"", t->key );
187     }
188     av_dict_free(pp_dict);
189 }
190
191 static void FindStreamInfo( demux_t *p_demux, AVDictionary *options )
192 {
193     demux_sys_t *p_sys = p_demux->p_sys;
194     unsigned nb_streams = p_sys->ic->nb_streams;
195
196     AVDictionary *streamsoptions[nb_streams ? nb_streams : 1];
197
198     streamsoptions[0] = options;
199     for ( unsigned i = 1; i < nb_streams; i++ )
200     {
201         streamsoptions[i] = NULL;
202         if( streamsoptions[0] )
203             av_dict_copy( &streamsoptions[i], streamsoptions[0], 0 );
204     }
205
206     vlc_avcodec_lock(); /* avformat calls avcodec behind our back!!! */
207     int error = avformat_find_stream_info( p_sys->ic, streamsoptions );
208     vlc_avcodec_unlock();
209
210     FreeUnclaimedOptions( p_demux, &streamsoptions[0] );
211     for ( unsigned i = 1; i < nb_streams; i++ ) {
212         av_dict_free( &streamsoptions[i] );
213     }
214
215     if( error < 0 )
216     {
217         msg_Warn( p_demux, "Could not find stream info: %s",
218                   vlc_strerror_c(AVUNERROR(error)) );
219     }
220 }
221
222 static int avformat_ProbeDemux( vlc_object_t *p_this,
223                                 AVInputFormat **pp_fmt, const char *psz_url )
224 {
225     demux_t       *p_demux = (demux_t*)p_this;
226     AVProbeData   pd = { 0 };
227     const uint8_t *peek;
228
229     /* Init Probe data */
230     pd.buf_size = vlc_stream_Peek( p_demux->s, &peek, 2048 + 213 );
231     if( pd.buf_size <= 0 )
232     {
233         msg_Warn( p_demux, "cannot peek" );
234         return VLC_EGENERIC;
235     }
236
237     pd.buf = malloc( pd.buf_size + AVPROBE_PADDING_SIZE );
238     if( unlikely(pd.buf == NULL) )
239         return VLC_ENOMEM;
240
241     memcpy( pd.buf, peek, pd.buf_size );
242     memset( pd.buf + pd.buf_size, 0, AVPROBE_PADDING_SIZE );
243
244     if( psz_url != NULL )
245         msg_Dbg( p_demux, "trying url: %s", psz_url );
246
247     pd.filename = psz_url;
248
249     vlc_init_avformat(p_this);
250
251     /* Guess format */
252     char *psz_format = var_InheritString( p_this, "avformat-format" );
253     if( psz_format )
254     {
255         if( (*pp_fmt = av_find_input_format(psz_format)) )
256             msg_Dbg( p_demux, "forcing format: %s", (*pp_fmt)->name );
257         free( psz_format );
258     }
259
260     if( *pp_fmt == NULL )
261         *pp_fmt = av_probe_input_format( &pd, 1 );
262
263     free( pd.buf );
264
265     if( *pp_fmt == NULL )
266     {
267         msg_Dbg( p_demux, "couldn't guess format" );
268         return VLC_EGENERIC;
269     }
270
271     if( !p_demux->obj.force )
272     {
273         static const char ppsz_blacklist[][16] = {
274             /* Don't handle MPEG unless forced */
275             "mpeg", "vcd", "vob", "mpegts",
276             /* libavformat's redirector won't work */
277             "redir", "sdp",
278             /* Don't handle subtitles format */
279             "ass", "srt", "microdvd",
280             /* No timestamps at all */
281             "hevc", "h264",
282             ""
283         };
284
285         for( int i = 0; *ppsz_blacklist[i]; i++ )
286         {
287             if( !strcmp( (*pp_fmt)->name, ppsz_blacklist[i] ) )
288                 return VLC_EGENERIC;
289         }
290     }
291
292     /* Don't trigger false alarms on bin files */
293     if( !p_demux->obj.force && !strcmp( (*pp_fmt)->name, "psxstr" ) )
294     {
295         int i_len;
296
297         if( !p_demux->psz_filepath )
298             return VLC_EGENERIC;
299
300         i_len = strlen( p_demux->psz_filepath );
301         if( i_len < 4 )
302             return VLC_EGENERIC;
303
304         if( strcasecmp( &p_demux->psz_filepath[i_len - 4], ".str" ) &&
305             strcasecmp( &p_demux->psz_filepath[i_len - 4], ".xai" ) &&
306             strcasecmp( &p_demux->psz_filepath[i_len - 3], ".xa" ) )
307         {
308             return VLC_EGENERIC;
309         }
310     }
311
312     msg_Dbg( p_demux, "detected format: %s", (*pp_fmt)->name );
313
314     return VLC_SUCCESS;
315 }
316
317 int avformat_OpenDemux( vlc_object_t *p_this )
318 {
319     demux_t       *p_demux = (demux_t*)p_this;
320     demux_sys_t   *p_sys;
321     AVInputFormat *fmt = NULL;
322     vlc_tick_t    i_start_time = VLC_TICK_INVALID;
323     bool          b_can_seek;
324     const char    *psz_url;
325     int           error;
326
327     if( p_demux->psz_filepath )
328         psz_url = p_demux->psz_filepath;
329     else
330         psz_url = p_demux->psz_url;
331
332     if( avformat_ProbeDemux( p_this, &fmt, psz_url ) != VLC_SUCCESS )
333         return VLC_EGENERIC;
334
335     vlc_stream_Control( p_demux->s, STREAM_CAN_SEEK, &b_can_seek );
336
337     /* Fill p_demux fields */
338     p_demux->pf_demux = Demux;
339     p_demux->pf_control = Control;
340     p_demux->p_sys = p_sys = malloc( sizeof( demux_sys_t ) );
341     if( !p_sys )
342         return VLC_ENOMEM;
343
344     p_sys->ic = 0;
345     p_sys->fmt = fmt;
346     p_sys->tracks = NULL;
347     p_sys->i_ssa_order = 0;
348     TAB_INIT( p_sys->i_attachments, p_sys->attachments);
349     p_sys->p_title = NULL;
350     p_sys->i_seekpoint = 0;
351     p_sys->i_update = 0;
352
353     /* Create I/O wrapper */
354     unsigned char * p_io_buffer = av_malloc( AVFORMAT_IOBUFFER_SIZE );
355     if( !p_io_buffer )
356     {
357         avformat_CloseDemux( p_this );
358         return VLC_ENOMEM;
359     }
360
361     p_sys->ic = avformat_alloc_context();
362     if( !p_sys->ic )
363     {
364         av_free( p_io_buffer );
365         avformat_CloseDemux( p_this );
366         return VLC_ENOMEM;
367     }
368
369     AVIOContext *pb = p_sys->ic->pb = avio_alloc_context( p_io_buffer,
370         AVFORMAT_IOBUFFER_SIZE, 0, p_demux, IORead, NULL, IOSeek );
371     if( !pb )
372     {
373         av_free( p_io_buffer );
374         avformat_CloseDemux( p_this );
375         return VLC_ENOMEM;
376     }
377
378     /* get all options, open_input will consume its own options from the dict */
379     AVDictionary *options = BuildAVOptions( p_demux );
380
381     p_sys->ic->pb->seekable = b_can_seek ? AVIO_SEEKABLE_NORMAL : 0;
382     error = avformat_open_input( &p_sys->ic, psz_url, p_sys->fmt, &options );
383     if( error < 0 )
384     {
385         msg_Err( p_demux, "Could not open %s: %s", psz_url,
386                  vlc_strerror_c(AVUNERROR(error)) );
387         av_dict_free( &options );
388         av_free( pb->buffer );
389         av_free( pb );
390         p_sys->ic = NULL;
391         avformat_CloseDemux( p_this );
392         return VLC_EGENERIC;
393     }
394
395     /* pass remaining options for as streams options */
396     FindStreamInfo( p_demux, options );
397
398     unsigned nb_streams = p_sys->ic->nb_streams; /* it may have changed */
399     if( !nb_streams )
400     {
401         msg_Err( p_demux, "No streams found");
402         avformat_CloseDemux( p_this );
403         return VLC_EGENERIC;
404     }
405     p_sys->tracks = calloc( nb_streams, sizeof(*p_sys->tracks) );
406     if( !p_sys->tracks )
407     {
408         avformat_CloseDemux( p_this );
409         return VLC_ENOMEM;
410     }
411     p_sys->i_tracks = nb_streams;
412
413     if( error < 0 )
414     {
415         msg_Warn( p_demux, "Could not find stream info: %s",
416                   vlc_strerror_c(AVUNERROR(error)) );
417     }
418
419     for( unsigned i = 0; i < nb_streams; i++ )
420     {
421         struct avformat_track_s *p_track = &p_sys->tracks[i];
422         AVStream *s = p_sys->ic->streams[i];
423         const AVCodecParameters *cp = s->codecpar;
424         es_format_t es_fmt;
425         const char *psz_type = "unknown";
426
427         /* Do not use the cover art as a stream */
428         if( s->disposition == AV_DISPOSITION_ATTACHED_PIC )
429             continue;
430
431         vlc_fourcc_t fcc = GetVlcFourcc( cp->codec_id );
432         switch( cp->codec_type )
433         {
434         case AVMEDIA_TYPE_AUDIO:
435             es_format_Init( &es_fmt, AUDIO_ES, fcc );
436             es_fmt.i_original_fourcc = CodecTagToFourcc( cp->codec_tag );
437             es_fmt.i_bitrate = cp->bit_rate;
438             es_fmt.audio.i_channels = cp->channels;
439             es_fmt.audio.i_rate = cp->sample_rate;
440             es_fmt.audio.i_bitspersample = cp->bits_per_coded_sample;
441             es_fmt.audio.i_blockalign = cp->block_align;
442             psz_type = "audio";
443
444             if(cp->codec_id == AV_CODEC_ID_AAC_LATM)
445             {
446                 es_fmt.i_original_fourcc = VLC_FOURCC('L','A','T','M');
447                 es_fmt.b_packetized = false;
448             }
449             else if(cp->codec_id == AV_CODEC_ID_AAC && p_sys->fmt->long_name &&
450                     strstr(p_sys->fmt->long_name, "raw ADTS AAC"))
451             {
452                 es_fmt.i_original_fourcc = VLC_FOURCC('A','D','T','S');
453                 es_fmt.b_packetized = false;
454             }
455             break;
456
457         case AVMEDIA_TYPE_VIDEO:
458             es_format_Init( &es_fmt, VIDEO_ES, fcc );
459             es_fmt.i_original_fourcc = CodecTagToFourcc( cp->codec_tag );
460
461             es_fmt.video.i_bits_per_pixel = cp->bits_per_coded_sample;
462             /* Special case for raw video data */
463             if( cp->codec_id == AV_CODEC_ID_RAWVIDEO )
464             {
465                 msg_Dbg( p_demux, "raw video, pixel format: %i", cp->format );
466                 if( GetVlcChroma( &es_fmt.video, cp->format ) != VLC_SUCCESS)
467                 {
468                     msg_Err( p_demux, "was unable to find a FourCC match for raw video" );
469                 }
470                 else
471                     es_fmt.i_codec = es_fmt.video.i_chroma;
472             }
473             /* We need this for the h264 packetizer */
474             else if( cp->codec_id == AV_CODEC_ID_H264 && ( p_sys->fmt == av_find_input_format("flv") ||
475                 p_sys->fmt == av_find_input_format("matroska") || p_sys->fmt == av_find_input_format("mp4") ) )
476                 es_fmt.i_original_fourcc = VLC_FOURCC( 'a', 'v', 'c', '1' );
477
478             es_fmt.video.i_width = cp->width;
479             es_fmt.video.i_height = cp->height;
480             es_fmt.video.i_visible_width = es_fmt.video.i_width;
481             es_fmt.video.i_visible_height = es_fmt.video.i_height;
482
483             get_rotation(&es_fmt, s);
484
485 # warning FIXME: implement palette transmission
486             psz_type = "video";
487
488             AVRational rate;
489 #if (LIBAVUTIL_VERSION_MICRO < 100) /* libav */
490 # if (LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(55, 20, 0))
491             rate.num = s->time_base.num;
492             rate.den = s->time_base.den;
493 # else
494             rate.num = s->codec->time_base.num;
495             rate.den = s->codec->time_base.den;
496 # endif
497             rate.den *= __MAX( s->codec->ticks_per_frame, 1 );
498 #else /* ffmpeg */
499             rate = av_guess_frame_rate( p_sys->ic, s, NULL );
500 #endif
501             if( rate.den && rate.num )
502             {
503                 es_fmt.video.i_frame_rate = rate.num;
504                 es_fmt.video.i_frame_rate_base = rate.den;
505             }
506
507             AVRational ar;
508 #if (LIBAVUTIL_VERSION_MICRO < 100) /* libav */
509             ar.num = s->sample_aspect_ratio.num;
510             ar.den = s->sample_aspect_ratio.den;
511 #else
512             ar = av_guess_sample_aspect_ratio( p_sys->ic, s, NULL );
513 #endif
514             if( ar.num && ar.den )
515             {
516                 es_fmt.video.i_sar_den = ar.den;
517                 es_fmt.video.i_sar_num = ar.num;
518             }
519             break;
520
521         case AVMEDIA_TYPE_SUBTITLE:
522             es_format_Init( &es_fmt, SPU_ES, fcc );
523             es_fmt.i_original_fourcc = CodecTagToFourcc( cp->codec_tag );
524             if( strncmp( p_sys->ic->iformat->name, "matroska", 8 ) == 0 &&
525                 cp->codec_id == AV_CODEC_ID_DVD_SUBTITLE &&
526                 cp->extradata != NULL &&
527                 cp->extradata_size > 0 )
528             {
529                 char *psz_start;
530                 char *psz_buf = malloc( cp->extradata_size + 1);
531                 if( psz_buf != NULL )
532                 {
533                     memcpy( psz_buf, cp->extradata , cp->extradata_size );
534                     psz_buf[cp->extradata_size] = '\0';
535
536                     psz_start = strstr( psz_buf, "size:" );
537                     if( psz_start &&
538                         vobsub_size_parse( psz_start,
539                                            &es_fmt.subs.spu.i_original_frame_width,
540                                            &es_fmt.subs.spu.i_original_frame_height ) == VLC_SUCCESS )
541                     {
542                         msg_Dbg( p_demux, "original frame size: %dx%d",
543                                  es_fmt.subs.spu.i_original_frame_width,
544                                  es_fmt.subs.spu.i_original_frame_height );
545                     }
546                     else
547                     {
548                         msg_Warn( p_demux, "reading original frame size failed" );
549                     }
550
551                     psz_start = strstr( psz_buf, "palette:" );
552                     if( psz_start &&
553                         vobsub_palette_parse( psz_start, &es_fmt.subs.spu.palette[1] ) == VLC_SUCCESS )
554                     {
555                         es_fmt.subs.spu.palette[0] = SPU_PALETTE_DEFINED;
556                         msg_Dbg( p_demux, "vobsub palette read" );
557                     }
558                     else
559                     {
560                         msg_Warn( p_demux, "reading original palette failed" );
561                     }
562                     free( psz_buf );
563                 }
564             }
565             else if( cp->codec_id == AV_CODEC_ID_DVB_SUBTITLE &&
566                      cp->extradata_size > 3 )
567             {
568                 es_fmt.subs.dvb.i_id = GetWBE( cp->extradata ) |
569                                       (GetWBE( cp->extradata + 2 ) << 16);
570             }
571             else if( cp->codec_id == AV_CODEC_ID_MOV_TEXT )
572             {
573                 if( cp->extradata_size && (es_fmt.p_extra = malloc(cp->extradata_size)) )
574                 {
575                     memcpy( es_fmt.p_extra, cp->extradata, cp->extradata_size );
576                     es_fmt.i_extra = cp->extradata_size;
577                 }
578             }
579             psz_type = "subtitle";
580             break;
581
582         default:
583             es_format_Init( &es_fmt, UNKNOWN_ES, 0 );
584             es_fmt.i_original_fourcc = CodecTagToFourcc( cp->codec_tag );
585 #ifdef HAVE_AVUTIL_CODEC_ATTACHMENT
586             if( cp->codec_type == AVMEDIA_TYPE_ATTACHMENT )
587             {
588                 input_attachment_t *p_attachment;
589
590                 psz_type = "attachment";
591                 if( cp->codec_id == AV_CODEC_ID_TTF )
592                 {
593                     AVDictionaryEntry *filename = av_dict_get( s->metadata, "filename", NULL, 0 );
594                     if( filename && filename->value )
595                     {
596                         p_attachment = vlc_input_attachment_New(
597                                 filename->value, "application/x-truetype-font",
598                                 NULL, cp->extradata, (int)cp->extradata_size );
599                         if( p_attachment )
600                             TAB_APPEND( p_sys->i_attachments, p_sys->attachments,
601                                         p_attachment );
602                     }
603                 }
604                 else msg_Warn( p_demux, "unsupported attachment type (%u) in avformat demux", cp->codec_id );
605             }
606             else
607 #endif
608             {
609                 if( cp->codec_type == AVMEDIA_TYPE_DATA )
610                     psz_type = "data";
611
612                 msg_Warn( p_demux, "unsupported track type (%u:%u) in avformat demux", cp->codec_type, cp->codec_id );
613             }
614             break;
615         }
616
617         AVDictionaryEntry *language = av_dict_get( s->metadata, "language", NULL, 0 );
618         if ( language && language->value )
619             es_fmt.psz_language = strdup( language->value );
620
621         if( s->disposition & AV_DISPOSITION_DEFAULT )
622             es_fmt.i_priority = ES_PRIORITY_SELECTABLE_MIN + 1000;
623
624 #ifdef HAVE_AVUTIL_CODEC_ATTACHMENT
625         if( cp->codec_type != AVMEDIA_TYPE_ATTACHMENT )
626 #endif
627         if( cp->codec_type != AVMEDIA_TYPE_DATA )
628         {
629             const bool    b_ogg = !strcmp( p_sys->fmt->name, "ogg" );
630             const uint8_t *p_extra = cp->extradata;
631             unsigned      i_extra  = cp->extradata_size;
632
633             if( cp->codec_id == AV_CODEC_ID_THEORA && b_ogg )
634             {
635                 unsigned pi_size[3];
636                 const void *pp_data[3];
637                 unsigned i_count;
638                 for( i_count = 0; i_count < 3; i_count++ )
639                 {
640                     if( i_extra < 2 )
641                         break;
642                     pi_size[i_count] = GetWBE( p_extra );
643                     pp_data[i_count] = &p_extra[2];
644                     if( i_extra < pi_size[i_count] + 2 )
645                         break;
646
647                     p_extra += 2 + pi_size[i_count];
648                     i_extra -= 2 + pi_size[i_count];
649                 }
650                 if( i_count > 0 && xiph_PackHeaders( &es_fmt.i_extra, &es_fmt.p_extra,
651                                                      pi_size, pp_data, i_count ) )
652                 {
653                     es_fmt.i_extra = 0;
654                     es_fmt.p_extra = NULL;
655                 }
656             }
657             else if( cp->codec_id == AV_CODEC_ID_SPEEX && b_ogg )
658             {
659                 const uint8_t p_dummy_comment[] = {
660                     0, 0, 0, 0,
661                     0, 0, 0, 0,
662                 };
663                 unsigned pi_size[2];
664                 const void *pp_data[2];
665
666                 pi_size[0] = i_extra;
667                 pp_data[0] = p_extra;
668
669                 pi_size[1] = sizeof(p_dummy_comment);
670                 pp_data[1] = p_dummy_comment;
671
672                 if( pi_size[0] > 0 && xiph_PackHeaders( &es_fmt.i_extra, &es_fmt.p_extra,
673                                                         pi_size, pp_data, 2 ) )
674                 {
675                     es_fmt.i_extra = 0;
676                     es_fmt.p_extra = NULL;
677                 }
678             }
679             else if( cp->codec_id == AV_CODEC_ID_OPUS )
680             {
681                 const uint8_t p_dummy_comment[] = {
682                     'O', 'p', 'u', 's',
683                     'T', 'a', 'g', 's',
684                     0, 0, 0, 0, /* Vendor String length */
685                                 /* Vendor String */
686                     0, 0, 0, 0, /* User Comment List Length */
687
688                 };
689                 unsigned pi_size[2];
690                 const void *pp_data[2];
691
692                 pi_size[0] = i_extra;
693                 pp_data[0] = p_extra;
694
695                 pi_size[1] = sizeof(p_dummy_comment);
696                 pp_data[1] = p_dummy_comment;
697
698                 if( pi_size[0] > 0 && xiph_PackHeaders( &es_fmt.i_extra, &es_fmt.p_extra,
699                                                         pi_size, pp_data, 2 ) )
700                 {
701                     es_fmt.i_extra = 0;
702                     es_fmt.p_extra = NULL;
703                 }
704             }
705             else if( cp->extradata_size > 0 && !es_fmt.i_extra )
706             {
707                 es_fmt.p_extra = malloc( i_extra );
708                 if( es_fmt.p_extra )
709                 {
710                     es_fmt.i_extra = i_extra;
711                     memcpy( es_fmt.p_extra, p_extra, i_extra );
712                 }
713             }
714
715             es_fmt.i_id = i;
716             p_track->p_es = es_out_Add( p_demux->out, &es_fmt );
717             if( p_track->p_es && (s->disposition & AV_DISPOSITION_DEFAULT) )
718                 es_out_Control( p_demux->out, ES_OUT_SET_ES_DEFAULT, p_track->p_es );
719
720             msg_Dbg( p_demux, "adding es: %s codec = %4.4s (%d)",
721                      psz_type, (char*)&fcc, cp->codec_id  );
722         }
723         es_format_Clean( &es_fmt );
724     }
725
726     if( p_sys->ic->start_time != (int64_t)AV_NOPTS_VALUE )
727         i_start_time = FROM_AV_TS(p_sys->ic->start_time);
728
729     msg_Dbg( p_demux, "AVFormat(%s %s) supported stream", AVPROVIDER(LIBAVFORMAT), LIBAVFORMAT_IDENT );
730     msg_Dbg( p_demux, "    - format = %s (%s)",
731              p_sys->fmt->name, p_sys->fmt->long_name );
732     msg_Dbg( p_demux, "    - start time = %"PRId64, i_start_time );
733     msg_Dbg( p_demux, "    - duration = %"PRId64,
734              ( p_sys->ic->duration != (int64_t)AV_NOPTS_VALUE ) ?
735              FROM_AV_TS(p_sys->ic->duration) : -1 );
736
737     if( p_sys->ic->nb_chapters > 0 )
738     {
739         p_sys->p_title = vlc_input_title_New();
740         p_sys->p_title->i_length = FROM_AV_TS(p_sys->ic->duration);
741     }
742
743     for( unsigned i = 0; i < p_sys->ic->nb_chapters; i++ )
744     {
745         seekpoint_t *s = vlc_seekpoint_New();
746
747         AVDictionaryEntry *title = av_dict_get( p_sys->ic->metadata, "title", NULL, 0);
748         if( title && title->value )
749         {
750             s->psz_name = strdup( title->value );
751             EnsureUTF8( s->psz_name );
752             msg_Dbg( p_demux, "    - chapter %d: %s", i, s->psz_name );
753         }
754         s->i_time_offset = vlc_tick_from_samples( p_sys->ic->chapters[i]->start *
755             p_sys->ic->chapters[i]->time_base.num,
756             p_sys->ic->chapters[i]->time_base.den ) -
757             (i_start_time != VLC_TICK_INVALID ? i_start_time : 0 );
758         TAB_APPEND( p_sys->p_title->i_seekpoint, p_sys->p_title->seekpoint, s );
759     }
760
761     ResetTime( p_demux, 0 );
762     return VLC_SUCCESS;
763 }
764
765 /*****************************************************************************
766  * Close
767  *****************************************************************************/
768 void avformat_CloseDemux( vlc_object_t *p_this )
769 {
770     demux_t     *p_demux = (demux_t*)p_this;
771     demux_sys_t *p_sys = p_demux->p_sys;
772
773     free( p_sys->tracks );
774
775     if( p_sys->ic )
776     {
777         if( p_sys->ic->pb )
778         {
779             av_free( p_sys->ic->pb->buffer );
780             av_free( p_sys->ic->pb );
781         }
782         avformat_close_input( &p_sys->ic );
783     }
784
785     for( int i = 0; i < p_sys->i_attachments; i++ )
786         vlc_input_attachment_Delete( p_sys->attachments[i] );
787     TAB_CLEAN( p_sys->i_attachments, p_sys->attachments);
788
789     if( p_sys->p_title )
790         vlc_input_title_Delete( p_sys->p_title );
791
792     free( p_sys );
793 }
794
795 /*****************************************************************************
796  * Demux:
797  *****************************************************************************/
798 static int Demux( demux_t *p_demux )
799 {
800     demux_sys_t *p_sys = p_demux->p_sys;
801     AVPacket    pkt;
802     block_t     *p_frame;
803     vlc_tick_t  i_start_time;
804
805     /* Read a frame */
806     int i_av_ret = av_read_frame( p_sys->ic, &pkt );
807     if( i_av_ret )
808     {
809         /* Avoid EOF if av_read_frame returns AVERROR(EAGAIN) */
810         if( i_av_ret == AVERROR(EAGAIN) )
811             return 1;
812
813         return 0;
814     }
815     if( pkt.stream_index < 0 || (unsigned) pkt.stream_index >= p_sys->i_tracks )
816     {
817         av_packet_unref( &pkt );
818         return 1;
819     }
820     struct avformat_track_s *p_track = &p_sys->tracks[pkt.stream_index];
821     const AVStream *p_stream = p_sys->ic->streams[pkt.stream_index];
822     if( p_stream->time_base.den <= 0 )
823     {
824         msg_Warn( p_demux, "Invalid time base for the stream %d", pkt.stream_index );
825         av_packet_unref( &pkt );
826         return 1;
827     }
828     if( p_stream->codecpar->codec_id == AV_CODEC_ID_SSA )
829     {
830         p_frame = BuildSsaFrame( &pkt, p_sys->i_ssa_order++ );
831         if( !p_frame )
832         {
833             av_packet_unref( &pkt );
834             return 1;
835         }
836     }
837     else if( p_stream->codecpar->codec_id == AV_CODEC_ID_DVB_SUBTITLE )
838     {
839         if( ( p_frame = block_Alloc( pkt.size + 3 ) ) == NULL )
840         {
841             av_packet_unref( &pkt );
842             return 0;
843         }
844         p_frame->p_buffer[0] = 0x20;
845         p_frame->p_buffer[1] = 0x00;
846         memcpy( &p_frame->p_buffer[2], pkt.data, pkt.size );
847         p_frame->p_buffer[p_frame->i_buffer - 1] = 0x3f;
848     }
849     else
850     {
851         if( ( p_frame = block_Alloc( pkt.size ) ) == NULL )
852         {
853             av_packet_unref( &pkt );
854             return 0;
855         }
856         memcpy( p_frame->p_buffer, pkt.data, pkt.size );
857     }
858
859     if( pkt.flags & AV_PKT_FLAG_KEY )
860         p_frame->i_flags |= BLOCK_FLAG_TYPE_I;
861
862     /* Used to avoid timestamps overlow */
863     if( p_sys->ic->start_time != (int64_t)AV_NOPTS_VALUE )
864     {
865         i_start_time = vlc_tick_from_frac(p_sys->ic->start_time, AV_TIME_BASE);
866     }
867     else
868         i_start_time = 0;
869
870     if( pkt.dts == (int64_t)AV_NOPTS_VALUE )
871         p_frame->i_dts = VLC_TICK_INVALID;
872     else
873     {
874         p_frame->i_dts = vlc_tick_from_frac( pkt.dts * p_stream->time_base.num, p_stream->time_base.den )
875                 - i_start_time + VLC_TICK_0;
876     }
877
878     if( pkt.pts == (int64_t)AV_NOPTS_VALUE )
879         p_frame->i_pts = VLC_TICK_INVALID;
880     else
881     {
882         p_frame->i_pts = vlc_tick_from_frac( pkt.pts * p_stream->time_base.num, p_stream->time_base.den )
883                 - i_start_time + VLC_TICK_0;
884     }
885     if( pkt.duration > 0 && p_frame->i_length <= 0 )
886         p_frame->i_length = vlc_tick_from_samples(pkt.duration *
887             p_stream->time_base.num,
888             p_stream->time_base.den );
889
890     /* Add here notoriously bugged file formats/samples */
891     if( !strcmp( p_sys->fmt->name, "flv" ) )
892     {
893         /* FLV and video PTS */
894         if( p_stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
895             pkt.dts != (int64_t)AV_NOPTS_VALUE && pkt.dts == pkt.pts )
896                 p_frame->i_pts = VLC_TICK_INVALID;
897
898         /* Handle broken dts/pts increase with AAC. Duration is correct.
899          * sky_the80s_aacplus.flv #8195 */
900         if( p_stream->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
901             p_stream->codecpar->codec_id == AV_CODEC_ID_AAC )
902         {
903             if( p_track->i_pcr != VLC_TICK_INVALID &&
904                 p_track->i_pcr + p_frame->i_length > p_frame->i_dts )
905             {
906                 p_frame->i_dts = p_frame->i_pts = p_track->i_pcr + p_frame->i_length;
907             }
908         }
909     }
910 #ifdef AVFORMAT_DEBUG
911     msg_Dbg( p_demux, "tk[%d] dts=%"PRId64" pts=%"PRId64,
912              pkt.stream_index, p_frame->i_dts, p_frame->i_pts );
913 #endif
914     if( p_frame->i_dts != VLC_TICK_INVALID && p_track->p_es != NULL )
915         p_track->i_pcr = p_frame->i_dts;
916
917     vlc_tick_t i_ts_max = INT64_MIN;
918     for( unsigned i = 0; i < p_sys->i_tracks; i++ )
919     {
920         if( p_sys->tracks[i].p_es != NULL )
921             i_ts_max = __MAX( i_ts_max, p_sys->tracks[i].i_pcr );
922     }
923
924     vlc_tick_t i_ts_min = INT64_MAX;
925     for( unsigned i = 0; i < p_sys->i_tracks; i++ )
926     {
927         if( p_sys->tracks[i].p_es != NULL &&
928                 p_sys->tracks[i].i_pcr != VLC_TICK_INVALID &&
929                 p_sys->tracks[i].i_pcr + VLC_TICK_FROM_SEC(10)>= i_ts_max )
930             i_ts_min = __MIN( i_ts_min, p_sys->tracks[i].i_pcr );
931     }
932     if( i_ts_min >= p_sys->i_pcr && likely(i_ts_min != INT64_MAX) )
933     {
934         p_sys->i_pcr = i_ts_min;
935         es_out_SetPCR( p_demux->out, p_sys->i_pcr );
936         UpdateSeekPoint( p_demux, p_sys->i_pcr );
937     }
938
939     if( p_track->p_es != NULL )
940         es_out_Send( p_demux->out, p_track->p_es, p_frame );
941     else
942         block_Release( p_frame );
943
944     av_packet_unref( &pkt );
945     return 1;
946 }
947
948 static void UpdateSeekPoint( demux_t *p_demux, vlc_tick_t i_time )
949 {
950     demux_sys_t *p_sys = p_demux->p_sys;
951     int i;
952
953     if( !p_sys->p_title )
954         return;
955
956     for( i = 0; i < p_sys->p_title->i_seekpoint; i++ )
957     {
958         if( i_time < p_sys->p_title->seekpoint[i]->i_time_offset )
959             break;
960     }
961     i--;
962
963     if( i != p_sys->i_seekpoint && i >= 0 )
964     {
965         p_sys->i_seekpoint = i;
966         p_sys->i_update |= INPUT_UPDATE_SEEKPOINT;
967     }
968 }
969
970 static void ResetTime( demux_t *p_demux, int64_t i_time )
971 {
972     demux_sys_t *p_sys = p_demux->p_sys;
973     vlc_tick_t t;
974
975     if( p_sys->ic->start_time == (int64_t)AV_NOPTS_VALUE || i_time < 0 )
976     {
977         t = VLC_TICK_INVALID;
978     }
979     else
980     {
981 #if CLOCK_FREQ == AV_TIME_BASE
982         t = FROM_AV_TS(i_time);
983 #else
984         lldiv_t q = lldiv( i_time, AV_TIME_BASE );
985         t = vlc_tick_from_sec(q.quot) + FROM_AV_TS(q.rem);
986 #endif
987
988         if( t == VLC_TICK_INVALID )
989             t = VLC_TICK_0;
990     }
991
992     p_sys->i_pcr = t;
993     for( unsigned i = 0; i < p_sys->i_tracks; i++ )
994         p_sys->tracks[i].i_pcr = VLC_TICK_INVALID;
995
996     if( t != VLC_TICK_INVALID )
997     {
998         es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, t );
999         UpdateSeekPoint( p_demux, t );
1000     }
1001 }
1002
1003 static block_t *BuildSsaFrame( const AVPacket *p_pkt, unsigned i_order )
1004 {
1005     if( p_pkt->size <= 0 )
1006         return NULL;
1007
1008     char buffer[256];
1009     const size_t i_buffer_size = __MIN( (int)sizeof(buffer) - 1, p_pkt->size );
1010     memcpy( buffer, p_pkt->data, i_buffer_size );
1011     buffer[i_buffer_size] = '\0';
1012
1013     /* */
1014     int i_layer;
1015     int h0, m0, s0, c0;
1016     int h1, m1, s1, c1;
1017     int i_position = 0;
1018     if( sscanf( buffer, "Dialogue: %d,%d:%d:%d.%d,%d:%d:%d.%d,%n", &i_layer,
1019                 &h0, &m0, &s0, &c0, &h1, &m1, &s1, &c1, &i_position ) < 9 )
1020         return NULL;
1021     if( i_position <= 0 || (unsigned)i_position >= i_buffer_size )
1022         return NULL;
1023
1024     char *p;
1025     if( asprintf( &p, "%u,%d,%.*s", i_order, i_layer, p_pkt->size - i_position, p_pkt->data + i_position ) < 0 )
1026         return NULL;
1027
1028     block_t *p_frame = block_heap_Alloc( p, strlen(p) + 1 );
1029     if( p_frame )
1030         p_frame->i_length = vlc_tick_from_sec((h1-h0) * 3600 +
1031                                          (m1-m0) * 60 +
1032                                          (s1-s0) * 1) +
1033                              VLC_TICK_FROM_MS (c1-c0) / 100;
1034     return p_frame;
1035 }
1036
1037 /*****************************************************************************
1038  * Control:
1039  *****************************************************************************/
1040 static int Control( demux_t *p_demux, int i_query, va_list args )
1041 {
1042     demux_sys_t *p_sys = p_demux->p_sys;
1043     const int64_t i_start_time = p_sys->ic->start_time != AV_NOPTS_VALUE ? p_sys->ic->start_time : 0;
1044     double f, *pf;
1045     int64_t i64;
1046
1047     switch( i_query )
1048     {
1049         case DEMUX_CAN_SEEK:
1050             *va_arg( args, bool * ) = true;
1051             return VLC_SUCCESS;
1052
1053         case DEMUX_GET_POSITION:
1054             pf = va_arg( args, double * ); *pf = 0.0;
1055             i64 = stream_Size( p_demux->s );
1056             if( i64 > 0 )
1057             {
1058                 double current = vlc_stream_Tell( p_demux->s );
1059                 *pf = current / (double)i64;
1060             }
1061
1062             if( (p_sys->ic->duration != (int64_t)AV_NOPTS_VALUE) && (p_sys->i_pcr > 0) )
1063             {
1064                 *pf = (double)p_sys->i_pcr / (double)p_sys->ic->duration;
1065             }
1066
1067             return VLC_SUCCESS;
1068
1069         case DEMUX_SET_POSITION:
1070         {
1071             f = va_arg( args, double );
1072             bool precise = va_arg( args, int );
1073             i64 = p_sys->ic->duration * f + i_start_time;
1074
1075             msg_Warn( p_demux, "DEMUX_SET_POSITION: %"PRId64, i64 );
1076
1077             /* If we have a duration, we prefer to seek by time
1078                but if we don't, or if the seek fails, try BYTE seeking */
1079             if( p_sys->ic->duration == (int64_t)AV_NOPTS_VALUE ||
1080                 (av_seek_frame( p_sys->ic, -1, i64, AVSEEK_FLAG_BACKWARD ) < 0) )
1081             {
1082                 int64_t i_size = stream_Size( p_demux->s );
1083                 i64 = (i_size * f);
1084
1085                 msg_Warn( p_demux, "DEMUX_SET_BYTE_POSITION: %"PRId64, i64 );
1086                 if( av_seek_frame( p_sys->ic, -1, i64, AVSEEK_FLAG_BYTE ) < 0 )
1087                     return VLC_EGENERIC;
1088
1089                 ResetTime( p_demux, -1 );
1090             }
1091             else
1092             {
1093                 if( precise )
1094                     ResetTime( p_demux, i64 - i_start_time );
1095                 else
1096                     ResetTime( p_demux, -1 );
1097             }
1098             return VLC_SUCCESS;
1099         }
1100
1101         case DEMUX_GET_LENGTH:
1102             if( p_sys->ic->duration != (int64_t)AV_NOPTS_VALUE )
1103                 *va_arg( args, vlc_tick_t * ) = FROM_AV_TS(p_sys->ic->duration);
1104             else
1105                 *va_arg( args, vlc_tick_t * ) = 0;
1106             return VLC_SUCCESS;
1107
1108         case DEMUX_GET_TIME:
1109             *va_arg( args, vlc_tick_t * ) = p_sys->i_pcr;
1110             return VLC_SUCCESS;
1111
1112         case DEMUX_SET_TIME:
1113         {
1114             i64 = TO_AV_TS(va_arg( args, vlc_tick_t ));
1115             bool precise = va_arg( args, int );
1116
1117             msg_Warn( p_demux, "DEMUX_SET_TIME: %"PRId64, i64 );
1118
1119             if( av_seek_frame( p_sys->ic, -1, i64 + i_start_time, AVSEEK_FLAG_BACKWARD ) < 0 )
1120             {
1121                 return VLC_EGENERIC;
1122             }
1123             if( precise )
1124                 ResetTime( p_demux, i64 - i_start_time );
1125             else
1126                 ResetTime( p_demux, -1 );
1127             return VLC_SUCCESS;
1128         }
1129
1130         case DEMUX_HAS_UNSUPPORTED_META:
1131         {
1132             bool *pb_bool = va_arg( args, bool* );
1133             *pb_bool = true;
1134             return VLC_SUCCESS;
1135         }
1136
1137
1138         case DEMUX_GET_META:
1139         {
1140             static const char names[][10] = {
1141                 [vlc_meta_Title] = "title",
1142                 [vlc_meta_Artist] = "artist",
1143                 [vlc_meta_Genre] = "genre",
1144                 [vlc_meta_Copyright] = "copyright",
1145                 [vlc_meta_Album] = "album",
1146                 //[vlc_meta_TrackNumber] -- TODO: parse number/total value
1147                 [vlc_meta_Description] = "comment",
1148                 //[vlc_meta_Rating]
1149                 [vlc_meta_Date] = "date",
1150                 [vlc_meta_Setting] = "encoder",
1151                 //[vlc_meta_URL]
1152                 [vlc_meta_Language] = "language",
1153                 //[vlc_meta_NowPlaying]
1154                 [vlc_meta_Publisher] = "publisher",
1155                 [vlc_meta_EncodedBy] = "encoded_by",
1156                 //[vlc_meta_ArtworkURL]
1157                 //[vlc_meta_TrackID]
1158                 //[vlc_meta_TrackTotal]
1159             };
1160             vlc_meta_t *p_meta = va_arg( args, vlc_meta_t * );
1161             AVDictionary *dict = p_sys->ic->metadata;
1162
1163             for( unsigned i = 0; i < sizeof(names) / sizeof(*names); i++)
1164             {
1165                 if( !names[i][0] )
1166                     continue;
1167
1168                 AVDictionaryEntry *e = av_dict_get( dict, names[i], NULL, 0 );
1169                 if( e != NULL && e->value != NULL && IsUTF8(e->value) )
1170                     vlc_meta_Set( p_meta, i, e->value );
1171             }
1172             return VLC_SUCCESS;
1173         }
1174
1175         case DEMUX_GET_ATTACHMENTS:
1176         {
1177             input_attachment_t ***ppp_attach =
1178                 va_arg( args, input_attachment_t*** );
1179             int *pi_int = va_arg( args, int * );
1180             int i;
1181
1182             if( p_sys->i_attachments <= 0 )
1183                 return VLC_EGENERIC;
1184
1185             *ppp_attach = vlc_alloc( p_sys->i_attachments, sizeof(input_attachment_t*) );
1186             if( *ppp_attach == NULL )
1187                 return VLC_EGENERIC;
1188
1189             for( i = 0; i < p_sys->i_attachments; i++ )
1190             {
1191                 (*ppp_attach)[i] = vlc_input_attachment_Duplicate( p_sys->attachments[i] );
1192                 if((*ppp_attach)[i] == NULL)
1193                     break;
1194             }
1195             *pi_int = i;
1196             return VLC_SUCCESS;
1197         }
1198
1199         case DEMUX_GET_TITLE_INFO:
1200         {
1201             input_title_t ***ppp_title = va_arg( args, input_title_t *** );
1202             int *pi_int = va_arg( args, int * );
1203             int *pi_title_offset = va_arg( args, int * );
1204             int *pi_seekpoint_offset = va_arg( args, int * );
1205
1206             if( !p_sys->p_title )
1207                 return VLC_EGENERIC;
1208
1209             *ppp_title = malloc( sizeof( input_title_t*) );
1210             if( *ppp_title == NULL )
1211                 return VLC_EGENERIC;
1212             (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->p_title );
1213             *pi_int = (*ppp_title)[0] ? 1 : 0;
1214             *pi_title_offset = 0;
1215             *pi_seekpoint_offset = 0;
1216             return VLC_SUCCESS;
1217         }
1218         case DEMUX_SET_TITLE:
1219         {
1220             const int i_title = va_arg( args, int );
1221             if( !p_sys->p_title || i_title != 0 )
1222                 return VLC_EGENERIC;
1223             return VLC_SUCCESS;
1224         }
1225         case DEMUX_SET_SEEKPOINT:
1226         {
1227             const int i_seekpoint = va_arg( args, int );
1228             if( !p_sys->p_title )
1229                 return VLC_EGENERIC;
1230
1231             i64 = TO_AV_TS(p_sys->p_title->seekpoint[i_seekpoint]->i_time_offset) +
1232                   i_start_time;
1233
1234             msg_Warn( p_demux, "DEMUX_SET_SEEKPOINT: %"PRId64, i64 );
1235
1236             if( av_seek_frame( p_sys->ic, -1, i64, AVSEEK_FLAG_BACKWARD ) < 0 )
1237             {
1238                 return VLC_EGENERIC;
1239             }
1240             ResetTime( p_demux, i64 - i_start_time );
1241             return VLC_SUCCESS;
1242         }
1243         case DEMUX_TEST_AND_CLEAR_FLAGS:
1244         {
1245             unsigned *restrict flags = va_arg(args, unsigned *);
1246             *flags &= p_sys->i_update;
1247             p_sys->i_update &= ~*flags;
1248             return VLC_SUCCESS;
1249         }
1250         case DEMUX_GET_TITLE:
1251             if( p_sys->p_title == NULL )
1252                 return VLC_EGENERIC;
1253             *va_arg( args, int * ) = 0;
1254             return VLC_SUCCESS;
1255         case DEMUX_GET_SEEKPOINT:
1256             if( p_sys->p_title == NULL )
1257                 return VLC_EGENERIC;
1258             *va_arg( args, int * ) = p_sys->i_seekpoint;
1259             return VLC_SUCCESS;
1260         case DEMUX_CAN_PAUSE:
1261         case DEMUX_SET_PAUSE_STATE:
1262         case DEMUX_CAN_CONTROL_PACE:
1263         case DEMUX_GET_PTS_DELAY:
1264             return demux_vaControlHelper( p_demux->s, 0, -1, 0, 1, i_query, args );
1265         default:
1266             return VLC_EGENERIC;
1267     }
1268 }
1269
1270 /*****************************************************************************
1271  * I/O wrappers for libavformat
1272  *****************************************************************************/
1273 static int IORead( void *opaque, uint8_t *buf, int buf_size )
1274 {
1275     demux_t *p_demux = opaque;
1276     if( buf_size < 0 ) return -1;
1277     int i_ret = vlc_stream_Read( p_demux->s, buf, buf_size );
1278     return i_ret >= 0 ? i_ret : -1;
1279 }
1280
1281 static int64_t IOSeek( void *opaque, int64_t offset, int whence )
1282 {
1283     demux_t *p_demux = opaque;
1284     int64_t i_absolute;
1285     int64_t i_size = stream_Size( p_demux->s );
1286
1287 #ifdef AVFORMAT_DEBUG
1288     msg_Warn( p_demux, "IOSeek offset: %"PRId64", whence: %i", offset, whence );
1289 #endif
1290
1291     switch( whence )
1292     {
1293 #ifdef AVSEEK_SIZE
1294         case AVSEEK_SIZE:
1295             return i_size;
1296 #endif
1297         case SEEK_SET:
1298             i_absolute = (int64_t)offset;
1299             break;
1300         case SEEK_CUR:
1301             i_absolute = vlc_stream_Tell( p_demux->s ) + (int64_t)offset;
1302             break;
1303         case SEEK_END:
1304             i_absolute = i_size + (int64_t)offset;
1305             break;
1306         default:
1307             return -1;
1308
1309     }
1310
1311     if( i_absolute < 0 )
1312     {
1313         msg_Dbg( p_demux, "Trying to seek before the beginning" );
1314         return -1;
1315     }
1316
1317     if( i_size > 0 && i_absolute >= i_size )
1318     {
1319         msg_Dbg( p_demux, "Trying to seek too far : EOF?" );
1320         return -1;
1321     }
1322
1323     if( vlc_stream_Seek( p_demux->s, i_absolute ) )
1324     {
1325         msg_Warn( p_demux, "we were not allowed to seek, or EOF " );
1326         return -1;
1327     }
1328
1329     return vlc_stream_Tell( p_demux->s );
1330 }