demux: avformat: fix incorrect PCR
[vlc.git] / modules / demux / avformat / demux.c
blob356c73f1f78d5483e41a186190bc8ffbeff62262
1 /*****************************************************************************
2 * demux.c: demuxer using libavformat
3 *****************************************************************************
4 * Copyright (C) 2004-2009 VLC authors and VideoLAN
5 * $Id$
7 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8 * Gildas Bazin <gbazin@videolan.org>
10 * This program is free software; you can redistribute it and/or modify it
11 * under the terms of the GNU Lesser General Public License as published by
12 * the Free Software Foundation; either version 2.1 of the License, or
13 * (at your option) any later version.
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 Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public License
21 * along with this program; if not, write to the Free Software Foundation,
22 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23 *****************************************************************************/
25 /*****************************************************************************
26 * Preamble
27 *****************************************************************************/
29 #ifdef HAVE_CONFIG_H
30 # include "config.h"
31 #endif
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>
41 #include "../../codec/avcodec/avcodec.h"
42 #include "../../codec/avcodec/chroma.h"
43 #include "../../codec/avcodec/avcommon_compat.h"
44 #include "avformat.h"
45 #include "../xiph.h"
46 #include "../vobsub.h"
48 #include <libavformat/avformat.h>
49 #include <libavutil/display.h>
51 //#define AVFORMAT_DEBUG 1
53 # define HAVE_AVUTIL_CODEC_ATTACHMENT 1
55 /*****************************************************************************
56 * demux_sys_t: demux descriptor
57 *****************************************************************************/
58 struct demux_sys_t
60 AVInputFormat *fmt;
61 AVFormatContext *ic;
63 int i_tk;
64 es_out_id_t **tk;
65 int64_t *tk_pcr;
66 int64_t i_pcr;
68 unsigned i_ssa_order;
70 int i_attachments;
71 input_attachment_t **attachments;
73 /* Only one title with seekpoints possible atm. */
74 input_title_t *p_title;
77 #define AVFORMAT_IOBUFFER_SIZE 32768 /* FIXME */
79 /*****************************************************************************
80 * Local prototypes
81 *****************************************************************************/
82 static int Demux ( demux_t *p_demux );
83 static int Control( demux_t *p_demux, int i_query, va_list args );
85 static int IORead( void *opaque, uint8_t *buf, int buf_size );
86 static int64_t IOSeek( void *opaque, int64_t offset, int whence );
88 static block_t *BuildSsaFrame( const AVPacket *p_pkt, unsigned i_order );
89 static void UpdateSeekPoint( demux_t *p_demux, int64_t i_time );
90 static void ResetTime( demux_t *p_demux, int64_t i_time );
92 static vlc_fourcc_t CodecTagToFourcc( uint32_t codec_tag )
94 // convert from little-endian avcodec codec_tag to VLC native-endian fourcc
95 #ifdef WORDS_BIGENDIAN
96 return bswap32(codec_tag);
97 #else
98 return codec_tag;
99 #endif
102 /*****************************************************************************
103 * Open
104 *****************************************************************************/
106 static void get_rotation(es_format_t *fmt, AVStream *s)
108 char const *kRotateKey = "rotate";
109 AVDictionaryEntry *rotation = av_dict_get(s->metadata, kRotateKey, NULL, 0);
110 long angle = 0;
112 if( rotation )
114 angle = strtol(rotation->value, NULL, 10);
116 if (angle > 45 && angle < 135)
117 fmt->video.orientation = ORIENT_ROTATED_90;
119 else if (angle > 135 && angle < 225)
120 fmt->video.orientation = ORIENT_ROTATED_180;
122 else if (angle > 225 && angle < 315)
123 fmt->video.orientation = ORIENT_ROTATED_270;
125 else
126 fmt->video.orientation = ORIENT_NORMAL;
128 int32_t *matrix = (int32_t *)av_stream_get_side_data(s, AV_PKT_DATA_DISPLAYMATRIX, NULL);
129 if( matrix ) {
130 angle = lround(av_display_rotation_get(matrix));
132 if (angle > 45 && angle < 135)
133 fmt->video.orientation = ORIENT_ROTATED_270;
135 else if (angle > 135 || angle < -135)
136 fmt->video.orientation = ORIENT_ROTATED_180;
138 else if (angle < -45 && angle > -135)
139 fmt->video.orientation = ORIENT_ROTATED_90;
141 else
142 fmt->video.orientation = ORIENT_NORMAL;
146 int OpenDemux( vlc_object_t *p_this )
148 demux_t *p_demux = (demux_t*)p_this;
149 demux_sys_t *p_sys;
150 AVProbeData pd = { };
151 AVInputFormat *fmt = NULL;
152 int64_t i_start_time = -1;
153 bool b_can_seek;
154 char *psz_url;
155 const uint8_t *peek;
156 int error;
158 /* Init Probe data */
159 pd.buf_size = vlc_stream_Peek( p_demux->s, &peek, 2048 + 213 );
160 if( pd.buf_size <= 0 )
162 msg_Warn( p_demux, "cannot peek" );
163 return VLC_EGENERIC;
166 pd.buf = malloc( pd.buf_size + AVPROBE_PADDING_SIZE );
167 if( unlikely(pd.buf == NULL) )
168 return VLC_ENOMEM;
170 memcpy( pd.buf, peek, pd.buf_size );
171 memset( pd.buf + pd.buf_size, 0, AVPROBE_PADDING_SIZE );
173 if( p_demux->psz_file )
174 psz_url = strdup( p_demux->psz_file );
175 else
177 if( asprintf( &psz_url, "%s://%s", p_demux->psz_access,
178 p_demux->psz_location ) == -1)
179 psz_url = NULL;
182 if( psz_url != NULL )
183 msg_Dbg( p_demux, "trying url: %s", psz_url );
185 pd.filename = psz_url;
187 vlc_stream_Control( p_demux->s, STREAM_CAN_SEEK, &b_can_seek );
189 vlc_init_avformat(p_this);
191 /* Guess format */
192 char *psz_format = var_InheritString( p_this, "avformat-format" );
193 if( psz_format )
195 if( (fmt = av_find_input_format(psz_format)) )
196 msg_Dbg( p_demux, "forcing format: %s", fmt->name );
197 free( psz_format );
200 if( fmt == NULL )
201 fmt = av_probe_input_format( &pd, 1 );
203 free( pd.buf );
205 if( fmt == NULL )
207 msg_Dbg( p_demux, "couldn't guess format" );
208 free( psz_url );
209 return VLC_EGENERIC;
212 if( !p_demux->obj.force )
214 static const char ppsz_blacklist[][16] = {
215 /* Don't handle MPEG unless forced */
216 "mpeg", "vcd", "vob", "mpegts",
217 /* libavformat's redirector won't work */
218 "redir", "sdp",
219 /* Don't handle subtitles format */
220 "ass", "srt", "microdvd",
221 /* No timestamps at all */
222 "hevc", "h264",
226 for( int i = 0; *ppsz_blacklist[i]; i++ )
228 if( !strcmp( fmt->name, ppsz_blacklist[i] ) )
230 free( psz_url );
231 return VLC_EGENERIC;
236 /* Don't trigger false alarms on bin files */
237 if( !p_demux->obj.force && !strcmp( fmt->name, "psxstr" ) )
239 int i_len;
241 if( !p_demux->psz_file )
243 free( psz_url );
244 return VLC_EGENERIC;
247 i_len = strlen( p_demux->psz_file );
248 if( i_len < 4 )
250 free( psz_url );
251 return VLC_EGENERIC;
254 if( strcasecmp( &p_demux->psz_file[i_len - 4], ".str" ) &&
255 strcasecmp( &p_demux->psz_file[i_len - 4], ".xai" ) &&
256 strcasecmp( &p_demux->psz_file[i_len - 3], ".xa" ) )
258 free( psz_url );
259 return VLC_EGENERIC;
263 msg_Dbg( p_demux, "detected format: %s", fmt->name );
265 /* Fill p_demux fields */
266 p_demux->pf_demux = Demux;
267 p_demux->pf_control = Control;
268 p_demux->p_sys = p_sys = xmalloc( sizeof( demux_sys_t ) );
269 p_sys->ic = 0;
270 p_sys->fmt = fmt;
271 p_sys->i_tk = 0;
272 p_sys->tk = NULL;
273 p_sys->tk_pcr = NULL;
274 p_sys->i_ssa_order = 0;
275 TAB_INIT( p_sys->i_attachments, p_sys->attachments);
276 p_sys->p_title = NULL;
278 /* Create I/O wrapper */
279 unsigned char * p_io_buffer = av_malloc( AVFORMAT_IOBUFFER_SIZE );
280 if( !p_io_buffer )
282 free( psz_url );
283 CloseDemux( p_this );
284 return VLC_ENOMEM;
287 p_sys->ic = avformat_alloc_context();
288 if( !p_sys->ic )
290 av_free( p_io_buffer );
291 free( psz_url );
292 CloseDemux( p_this );
293 return VLC_ENOMEM;
296 AVIOContext *pb = p_sys->ic->pb = avio_alloc_context( p_io_buffer,
297 AVFORMAT_IOBUFFER_SIZE, 0, p_demux, IORead, NULL, IOSeek );
298 if( !pb )
300 av_free( p_io_buffer );
301 free( psz_url );
302 CloseDemux( p_this );
303 return VLC_ENOMEM;
306 p_sys->ic->pb->seekable = b_can_seek ? AVIO_SEEKABLE_NORMAL : 0;
307 error = avformat_open_input(&p_sys->ic, psz_url, p_sys->fmt, NULL);
309 if( error < 0 )
311 msg_Err( p_demux, "Could not open %s: %s", psz_url,
312 vlc_strerror_c(AVUNERROR(error)) );
313 av_free( pb );
314 p_sys->ic = NULL;
315 free( psz_url );
316 CloseDemux( p_this );
317 return VLC_EGENERIC;
319 free( psz_url );
321 char *psz_opts = var_InheritString( p_demux, "avformat-options" );
322 AVDictionary *options[p_sys->ic->nb_streams ? p_sys->ic->nb_streams : 1];
323 options[0] = NULL;
324 unsigned int nb_streams = p_sys->ic->nb_streams;
325 for (unsigned i = 1; i < nb_streams; i++)
326 options[i] = NULL;
327 if (psz_opts) {
328 vlc_av_get_options(psz_opts, &options[0]);
329 for (unsigned i = 1; i < nb_streams; i++) {
330 av_dict_copy(&options[i], options[0], 0);
332 free(psz_opts);
334 vlc_avcodec_lock(); /* avformat calls avcodec behind our back!!! */
335 error = avformat_find_stream_info( p_sys->ic, options );
336 /* FIXME: what if nb_streams change after that call? */
337 vlc_avcodec_unlock();
338 AVDictionaryEntry *t = NULL;
339 while ((t = av_dict_get(options[0], "", t, AV_DICT_IGNORE_SUFFIX))) {
340 msg_Err( p_demux, "Unknown option \"%s\"", t->key );
342 av_dict_free(&options[0]);
343 for (unsigned i = 1; i < nb_streams; i++) {
344 av_dict_free(&options[i]);
347 if( error < 0 )
349 msg_Warn( p_demux, "Could not find stream info: %s",
350 vlc_strerror_c(AVUNERROR(error)) );
353 for( unsigned i = 0; i < p_sys->ic->nb_streams; i++ )
355 AVStream *s = p_sys->ic->streams[i];
356 const AVCodecParameters *cp = s->codecpar;
357 es_out_id_t *es = NULL;
358 es_format_t es_fmt;
359 const char *psz_type = "unknown";
361 /* Do not use the cover art as a stream */
362 if( s->disposition == AV_DISPOSITION_ATTACHED_PIC )
364 TAB_APPEND( p_sys->i_tk, p_sys->tk, NULL );
365 continue;
368 vlc_fourcc_t fcc = GetVlcFourcc( cp->codec_id );
369 switch( cp->codec_type )
371 case AVMEDIA_TYPE_AUDIO:
372 es_format_Init( &es_fmt, AUDIO_ES, fcc );
373 es_fmt.i_original_fourcc = CodecTagToFourcc( cp->codec_tag );
374 es_fmt.i_bitrate = cp->bit_rate;
375 es_fmt.audio.i_channels = cp->channels;
376 es_fmt.audio.i_rate = cp->sample_rate;
377 es_fmt.audio.i_bitspersample = cp->bits_per_coded_sample;
378 es_fmt.audio.i_blockalign = cp->block_align;
379 psz_type = "audio";
381 if(cp->codec_id == AV_CODEC_ID_AAC_LATM)
383 es_fmt.i_original_fourcc = VLC_FOURCC('L','A','T','M');
384 es_fmt.b_packetized = false;
386 else if(cp->codec_id == AV_CODEC_ID_AAC &&
387 strstr(p_sys->fmt->long_name, "raw ADTS AAC"))
389 es_fmt.i_original_fourcc = VLC_FOURCC('A','D','T','S');
390 es_fmt.b_packetized = false;
392 break;
394 case AVMEDIA_TYPE_VIDEO:
395 es_format_Init( &es_fmt, VIDEO_ES, fcc );
396 es_fmt.i_original_fourcc = CodecTagToFourcc( cp->codec_tag );
398 es_fmt.video.i_bits_per_pixel = cp->bits_per_coded_sample;
399 /* Special case for raw video data */
400 if( cp->codec_id == AV_CODEC_ID_RAWVIDEO )
402 msg_Dbg( p_demux, "raw video, pixel format: %i", cp->format );
403 if( GetVlcChroma( &es_fmt.video, cp->format ) != VLC_SUCCESS)
405 msg_Err( p_demux, "was unable to find a FourCC match for raw video" );
407 else
408 es_fmt.i_codec = es_fmt.video.i_chroma;
410 /* We need this for the h264 packetizer */
411 else if( cp->codec_id == AV_CODEC_ID_H264 && ( p_sys->fmt == av_find_input_format("flv") ||
412 p_sys->fmt == av_find_input_format("matroska") || p_sys->fmt == av_find_input_format("mp4") ) )
413 es_fmt.i_original_fourcc = VLC_FOURCC( 'a', 'v', 'c', '1' );
415 es_fmt.video.i_width = cp->width;
416 es_fmt.video.i_height = cp->height;
417 es_fmt.video.i_visible_width = es_fmt.video.i_width;
418 es_fmt.video.i_visible_height = es_fmt.video.i_height;
420 get_rotation(&es_fmt, s);
422 # warning FIXME: implement palette transmission
423 psz_type = "video";
424 es_fmt.video.i_frame_rate = s->codec->time_base.num;
425 es_fmt.video.i_frame_rate_base = s->codec->time_base.den * __MAX( s->codec->ticks_per_frame, 1 );
426 es_fmt.video.i_sar_num = s->sample_aspect_ratio.num;
427 if (s->sample_aspect_ratio.num > 0)
428 es_fmt.video.i_sar_den = s->sample_aspect_ratio.den;
429 else
430 es_fmt.video.i_sar_den = 0;
431 break;
433 case AVMEDIA_TYPE_SUBTITLE:
434 es_format_Init( &es_fmt, SPU_ES, fcc );
435 es_fmt.i_original_fourcc = CodecTagToFourcc( cp->codec_tag );
436 if( strncmp( p_sys->ic->iformat->name, "matroska", 8 ) == 0 &&
437 cp->codec_id == AV_CODEC_ID_DVD_SUBTITLE &&
438 cp->extradata != NULL &&
439 cp->extradata_size > 0 )
441 char *psz_start;
442 char *psz_buf = malloc( cp->extradata_size + 1);
443 if( psz_buf != NULL )
445 memcpy( psz_buf, cp->extradata , cp->extradata_size );
446 psz_buf[cp->extradata_size] = '\0';
448 psz_start = strstr( psz_buf, "size:" );
449 if( psz_start &&
450 vobsub_size_parse( psz_start,
451 &es_fmt.subs.spu.i_original_frame_width,
452 &es_fmt.subs.spu.i_original_frame_height ) == VLC_SUCCESS )
454 msg_Dbg( p_demux, "original frame size: %dx%d",
455 es_fmt.subs.spu.i_original_frame_width,
456 es_fmt.subs.spu.i_original_frame_height );
458 else
460 msg_Warn( p_demux, "reading original frame size failed" );
463 psz_start = strstr( psz_buf, "palette:" );
464 if( psz_start &&
465 vobsub_palette_parse( psz_start, &es_fmt.subs.spu.palette[1] ) == VLC_SUCCESS )
467 es_fmt.subs.spu.palette[0] = SPU_PALETTE_DEFINED;
468 msg_Dbg( p_demux, "vobsub palette read" );
470 else
472 msg_Warn( p_demux, "reading original palette failed" );
474 free( psz_buf );
478 psz_type = "subtitle";
479 break;
481 default:
482 es_format_Init( &es_fmt, UNKNOWN_ES, 0 );
483 es_fmt.i_original_fourcc = CodecTagToFourcc( cp->codec_tag );
484 #ifdef HAVE_AVUTIL_CODEC_ATTACHMENT
485 if( cp->codec_type == AVMEDIA_TYPE_ATTACHMENT )
487 input_attachment_t *p_attachment;
489 psz_type = "attachment";
490 if( cp->codec_id == AV_CODEC_ID_TTF )
492 AVDictionaryEntry *filename = av_dict_get( s->metadata, "filename", NULL, 0 );
493 if( filename && filename->value )
495 p_attachment = vlc_input_attachment_New(
496 filename->value, "application/x-truetype-font",
497 NULL, cp->extradata, (int)cp->extradata_size );
498 if( p_attachment )
499 TAB_APPEND( p_sys->i_attachments, p_sys->attachments,
500 p_attachment );
503 else msg_Warn( p_demux, "unsupported attachment type (%u) in avformat demux", cp->codec_id );
505 else
506 #endif
508 if( cp->codec_type == AVMEDIA_TYPE_DATA )
509 psz_type = "data";
511 msg_Warn( p_demux, "unsupported track type (%u:%u) in avformat demux", cp->codec_type, cp->codec_id );
513 break;
516 AVDictionaryEntry *language = av_dict_get( s->metadata, "language", NULL, 0 );
517 if ( language && language->value )
518 es_fmt.psz_language = strdup( language->value );
520 if( s->disposition & AV_DISPOSITION_DEFAULT )
521 es_fmt.i_priority = ES_PRIORITY_SELECTABLE_MIN + 1000;
523 #ifdef HAVE_AVUTIL_CODEC_ATTACHMENT
524 if( cp->codec_type != AVMEDIA_TYPE_ATTACHMENT )
525 #endif
526 if( cp->codec_type != AVMEDIA_TYPE_DATA )
528 const bool b_ogg = !strcmp( p_sys->fmt->name, "ogg" );
529 const uint8_t *p_extra = cp->extradata;
530 unsigned i_extra = cp->extradata_size;
532 if( cp->codec_id == AV_CODEC_ID_THEORA && b_ogg )
534 unsigned pi_size[3];
535 const void *pp_data[3];
536 unsigned i_count;
537 for( i_count = 0; i_count < 3; i_count++ )
539 if( i_extra < 2 )
540 break;
541 pi_size[i_count] = GetWBE( p_extra );
542 pp_data[i_count] = &p_extra[2];
543 if( i_extra < pi_size[i_count] + 2 )
544 break;
546 p_extra += 2 + pi_size[i_count];
547 i_extra -= 2 + pi_size[i_count];
549 if( i_count > 0 && xiph_PackHeaders( &es_fmt.i_extra, &es_fmt.p_extra,
550 pi_size, pp_data, i_count ) )
552 es_fmt.i_extra = 0;
553 es_fmt.p_extra = NULL;
556 else if( cp->codec_id == AV_CODEC_ID_SPEEX && b_ogg )
558 const uint8_t p_dummy_comment[] = {
559 0, 0, 0, 0,
560 0, 0, 0, 0,
562 unsigned pi_size[2];
563 const void *pp_data[2];
565 pi_size[0] = i_extra;
566 pp_data[0] = p_extra;
568 pi_size[1] = sizeof(p_dummy_comment);
569 pp_data[1] = p_dummy_comment;
571 if( pi_size[0] > 0 && xiph_PackHeaders( &es_fmt.i_extra, &es_fmt.p_extra,
572 pi_size, pp_data, 2 ) )
574 es_fmt.i_extra = 0;
575 es_fmt.p_extra = NULL;
578 else if( cp->codec_id == AV_CODEC_ID_OPUS )
580 const uint8_t p_dummy_comment[] = {
581 'O', 'p', 'u', 's',
582 'T', 'a', 'g', 's',
583 0, 0, 0, 0, /* Vendor String length */
584 /* Vendor String */
585 0, 0, 0, 0, /* User Comment List Length */
588 unsigned pi_size[2];
589 const void *pp_data[2];
591 pi_size[0] = i_extra;
592 pp_data[0] = p_extra;
594 pi_size[1] = sizeof(p_dummy_comment);
595 pp_data[1] = p_dummy_comment;
597 if( pi_size[0] > 0 && xiph_PackHeaders( &es_fmt.i_extra, &es_fmt.p_extra,
598 pi_size, pp_data, 2 ) )
600 es_fmt.i_extra = 0;
601 es_fmt.p_extra = NULL;
604 else if( cp->extradata_size > 0 )
606 es_fmt.p_extra = malloc( i_extra );
607 if( es_fmt.p_extra )
609 es_fmt.i_extra = i_extra;
610 memcpy( es_fmt.p_extra, p_extra, i_extra );
613 es = es_out_Add( p_demux->out, &es_fmt );
614 if( s->disposition & AV_DISPOSITION_DEFAULT )
615 es_out_Control( p_demux->out, ES_OUT_SET_ES_DEFAULT, es );
617 msg_Dbg( p_demux, "adding es: %s codec = %4.4s (%d)",
618 psz_type, (char*)&fcc, cp->codec_id );
620 es_format_Clean( &es_fmt );
621 TAB_APPEND( p_sys->i_tk, p_sys->tk, es );
623 p_sys->tk_pcr = xcalloc( p_sys->i_tk, sizeof(*p_sys->tk_pcr) );
625 if( p_sys->ic->start_time != (int64_t)AV_NOPTS_VALUE )
626 i_start_time = p_sys->ic->start_time * 1000000 / AV_TIME_BASE;
628 msg_Dbg( p_demux, "AVFormat(%s %s) supported stream", AVPROVIDER(LIBAVFORMAT), LIBAVFORMAT_IDENT );
629 msg_Dbg( p_demux, " - format = %s (%s)",
630 p_sys->fmt->name, p_sys->fmt->long_name );
631 msg_Dbg( p_demux, " - start time = %"PRId64, i_start_time );
632 msg_Dbg( p_demux, " - duration = %"PRId64,
633 ( p_sys->ic->duration != (int64_t)AV_NOPTS_VALUE ) ?
634 p_sys->ic->duration * 1000000 / AV_TIME_BASE : -1 );
636 if( p_sys->ic->nb_chapters > 0 )
638 p_sys->p_title = vlc_input_title_New();
639 p_sys->p_title->i_length = p_sys->ic->duration * 1000000 / AV_TIME_BASE;
642 for( unsigned i = 0; i < p_sys->ic->nb_chapters; i++ )
644 seekpoint_t *s = vlc_seekpoint_New();
646 AVDictionaryEntry *title = av_dict_get( p_sys->ic->metadata, "title", NULL, 0);
647 if( title && title->value )
649 s->psz_name = strdup( title->value );
650 EnsureUTF8( s->psz_name );
651 msg_Dbg( p_demux, " - chapter %d: %s", i, s->psz_name );
653 s->i_time_offset = p_sys->ic->chapters[i]->start * 1000000 *
654 p_sys->ic->chapters[i]->time_base.num /
655 p_sys->ic->chapters[i]->time_base.den -
656 (i_start_time != -1 ? i_start_time : 0 );
657 TAB_APPEND( p_sys->p_title->i_seekpoint, p_sys->p_title->seekpoint, s );
660 ResetTime( p_demux, 0 );
661 return VLC_SUCCESS;
664 /*****************************************************************************
665 * Close
666 *****************************************************************************/
667 void CloseDemux( vlc_object_t *p_this )
669 demux_t *p_demux = (demux_t*)p_this;
670 demux_sys_t *p_sys = p_demux->p_sys;
672 free( p_sys->tk );
673 free( p_sys->tk_pcr );
675 if( p_sys->ic )
677 if( p_sys->ic->pb )
679 av_free( p_sys->ic->pb->buffer );
680 av_free( p_sys->ic->pb );
682 avformat_close_input( &p_sys->ic );
685 for( int i = 0; i < p_sys->i_attachments; i++ )
686 vlc_input_attachment_Delete( p_sys->attachments[i] );
687 TAB_CLEAN( p_sys->i_attachments, p_sys->attachments);
689 if( p_sys->p_title )
690 vlc_input_title_Delete( p_sys->p_title );
692 free( p_sys );
695 /*****************************************************************************
696 * Demux:
697 *****************************************************************************/
698 static int Demux( demux_t *p_demux )
700 demux_sys_t *p_sys = p_demux->p_sys;
701 AVPacket pkt;
702 block_t *p_frame;
703 int64_t i_start_time;
705 /* Read a frame */
706 int i_av_ret = av_read_frame( p_sys->ic, &pkt );
707 if( i_av_ret )
709 /* Avoid EOF if av_read_frame returns AVERROR(EAGAIN) */
710 if( i_av_ret == AVERROR(EAGAIN) )
711 return 1;
713 return 0;
715 if( pkt.stream_index < 0 || pkt.stream_index >= p_sys->i_tk )
717 av_packet_unref( &pkt );
718 return 1;
720 const AVStream *p_stream = p_sys->ic->streams[pkt.stream_index];
721 if( p_stream->time_base.den <= 0 )
723 msg_Warn( p_demux, "Invalid time base for the stream %d", pkt.stream_index );
724 av_packet_unref( &pkt );
725 return 1;
727 if( p_stream->codecpar->codec_id == AV_CODEC_ID_SSA )
729 p_frame = BuildSsaFrame( &pkt, p_sys->i_ssa_order++ );
730 if( !p_frame )
732 av_packet_unref( &pkt );
733 return 1;
736 else
738 if( ( p_frame = block_Alloc( pkt.size ) ) == NULL )
740 av_packet_unref( &pkt );
741 return 0;
743 memcpy( p_frame->p_buffer, pkt.data, pkt.size );
746 if( pkt.flags & AV_PKT_FLAG_KEY )
747 p_frame->i_flags |= BLOCK_FLAG_TYPE_I;
749 /* Used to avoid timestamps overlow */
750 lldiv_t q;
751 if( p_sys->ic->start_time != (int64_t)AV_NOPTS_VALUE )
753 q = lldiv( p_sys->ic->start_time, AV_TIME_BASE);
754 i_start_time = q.quot * CLOCK_FREQ + q.rem * CLOCK_FREQ / AV_TIME_BASE;
756 else
757 i_start_time = 0;
759 if( pkt.dts == (int64_t)AV_NOPTS_VALUE )
760 p_frame->i_dts = VLC_TS_INVALID;
761 else
763 q = lldiv( pkt.dts, p_stream->time_base.den );
764 p_frame->i_dts = q.quot * CLOCK_FREQ *
765 p_stream->time_base.num + q.rem * CLOCK_FREQ *
766 p_stream->time_base.num /
767 p_stream->time_base.den - i_start_time + VLC_TS_0;
770 if( pkt.pts == (int64_t)AV_NOPTS_VALUE )
771 p_frame->i_pts = VLC_TS_INVALID;
772 else
774 q = lldiv( pkt.pts, p_stream->time_base.den );
775 p_frame->i_pts = q.quot * CLOCK_FREQ *
776 p_stream->time_base.num + q.rem * CLOCK_FREQ *
777 p_stream->time_base.num /
778 p_stream->time_base.den - i_start_time + VLC_TS_0;
780 if( pkt.duration > 0 && p_frame->i_length <= 0 )
781 p_frame->i_length = pkt.duration * CLOCK_FREQ *
782 p_stream->time_base.num /
783 p_stream->time_base.den;
785 /* Add here notoriously bugged file formats/samples */
786 if( !strcmp( p_sys->fmt->name, "flv" ) )
788 /* FLV and video PTS */
789 if( p_stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
790 pkt.dts != (int64_t)AV_NOPTS_VALUE && pkt.dts == pkt.pts )
791 p_frame->i_pts = VLC_TS_INVALID;
793 /* Handle broken dts/pts increase with AAC. Duration is correct.
794 * sky_the80s_aacplus.flv #8195 */
795 if( p_stream->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
796 p_stream->codecpar->codec_id == AV_CODEC_ID_AAC )
798 if( p_sys->tk_pcr[pkt.stream_index] != VLC_TS_INVALID &&
799 p_sys->tk_pcr[pkt.stream_index] + p_frame->i_length > p_frame->i_dts )
801 p_frame->i_dts = p_frame->i_pts = p_sys->tk_pcr[pkt.stream_index] + p_frame->i_length;
805 #ifdef AVFORMAT_DEBUG
806 msg_Dbg( p_demux, "tk[%d] dts=%"PRId64" pts=%"PRId64,
807 pkt.stream_index, p_frame->i_dts, p_frame->i_pts );
808 #endif
809 if( p_frame->i_dts > VLC_TS_INVALID )
810 p_sys->tk_pcr[pkt.stream_index] = p_frame->i_dts;
812 int64_t i_ts_max = INT64_MIN;
813 for( int i = 0; i < p_sys->i_tk; i++ )
814 i_ts_max = __MAX( i_ts_max, p_sys->tk_pcr[i] );
816 int64_t i_ts_min = INT64_MAX;
817 for( int i = 0; i < p_sys->i_tk; i++ )
819 if( p_sys->tk_pcr[i] > VLC_TS_INVALID && p_sys->tk_pcr[i] + 10 * CLOCK_FREQ >= i_ts_max )
820 i_ts_min = __MIN( i_ts_min, p_sys->tk_pcr[i] );
822 if( i_ts_min >= p_sys->i_pcr && likely(i_ts_min != INT64_MAX) )
824 p_sys->i_pcr = i_ts_min;
825 es_out_SetPCR( p_demux->out, p_sys->i_pcr );
826 UpdateSeekPoint( p_demux, p_sys->i_pcr );
829 if( p_sys->tk[pkt.stream_index] != NULL )
830 es_out_Send( p_demux->out, p_sys->tk[pkt.stream_index], p_frame );
831 else
832 block_Release( p_frame );
834 av_packet_unref( &pkt );
835 return 1;
838 static void UpdateSeekPoint( demux_t *p_demux, int64_t i_time )
840 demux_sys_t *p_sys = p_demux->p_sys;
841 int i;
843 if( !p_sys->p_title )
844 return;
846 for( i = 0; i < p_sys->p_title->i_seekpoint; i++ )
848 if( i_time < p_sys->p_title->seekpoint[i]->i_time_offset )
849 break;
851 i--;
853 if( i != p_demux->info.i_seekpoint && i >= 0 )
855 p_demux->info.i_seekpoint = i;
856 p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
860 static void ResetTime( demux_t *p_demux, int64_t i_time )
862 demux_sys_t *p_sys = p_demux->p_sys;
864 if( p_sys->ic->start_time == (int64_t)AV_NOPTS_VALUE || i_time < 0 )
865 i_time = VLC_TS_INVALID;
866 else if( i_time == 0 )
867 i_time = 1;
869 p_sys->i_pcr = i_time;
870 for( int i = 0; i < p_sys->i_tk; i++ )
871 p_sys->tk_pcr[i] = i_time;
873 if( i_time > VLC_TS_INVALID )
875 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, i_time );
876 UpdateSeekPoint( p_demux, i_time );
880 static block_t *BuildSsaFrame( const AVPacket *p_pkt, unsigned i_order )
882 if( p_pkt->size <= 0 )
883 return NULL;
885 char buffer[256];
886 const size_t i_buffer_size = __MIN( (int)sizeof(buffer) - 1, p_pkt->size );
887 memcpy( buffer, p_pkt->data, i_buffer_size );
888 buffer[i_buffer_size] = '\0';
890 /* */
891 int i_layer;
892 int h0, m0, s0, c0;
893 int h1, m1, s1, c1;
894 int i_position = 0;
895 if( sscanf( buffer, "Dialogue: %d,%d:%d:%d.%d,%d:%d:%d.%d,%n", &i_layer,
896 &h0, &m0, &s0, &c0, &h1, &m1, &s1, &c1, &i_position ) < 9 )
897 return NULL;
898 if( i_position <= 0 || (unsigned)i_position >= i_buffer_size )
899 return NULL;
901 char *p;
902 if( asprintf( &p, "%u,%d,%.*s", i_order, i_layer, p_pkt->size - i_position, p_pkt->data + i_position ) < 0 )
903 return NULL;
905 block_t *p_frame = block_heap_Alloc( p, strlen(p) + 1 );
906 if( p_frame )
907 p_frame->i_length = CLOCK_FREQ * ((h1-h0) * 3600 +
908 (m1-m0) * 60 +
909 (s1-s0) * 1) +
910 CLOCK_FREQ * (c1-c0) / 100;
911 return p_frame;
914 /*****************************************************************************
915 * Control:
916 *****************************************************************************/
917 static int Control( demux_t *p_demux, int i_query, va_list args )
919 demux_sys_t *p_sys = p_demux->p_sys;
920 const int64_t i_start_time = p_sys->ic->start_time != (int64_t)AV_NOPTS_VALUE ? p_sys->ic->start_time : 0;
921 double f, *pf;
922 int64_t i64, *pi64;
924 switch( i_query )
926 case DEMUX_CAN_SEEK:
927 *va_arg( args, bool * ) = true;
928 return VLC_SUCCESS;
930 case DEMUX_GET_POSITION:
931 pf = va_arg( args, double * ); *pf = 0.0;
932 i64 = stream_Size( p_demux->s );
933 if( i64 > 0 )
935 double current = vlc_stream_Tell( p_demux->s );
936 *pf = current / (double)i64;
939 if( (p_sys->ic->duration != (int64_t)AV_NOPTS_VALUE) && (p_sys->i_pcr > 0) )
941 *pf = (double)p_sys->i_pcr / (double)p_sys->ic->duration;
944 return VLC_SUCCESS;
946 case DEMUX_SET_POSITION:
947 f = va_arg( args, double );
948 i64 = p_sys->ic->duration * f + i_start_time;
950 msg_Warn( p_demux, "DEMUX_SET_POSITION: %"PRId64, i64 );
952 /* If we have a duration, we prefer to seek by time
953 but if we don't, or if the seek fails, try BYTE seeking */
954 if( p_sys->ic->duration == (int64_t)AV_NOPTS_VALUE ||
955 (av_seek_frame( p_sys->ic, -1, i64, AVSEEK_FLAG_BACKWARD ) < 0) )
957 int64_t i_size = stream_Size( p_demux->s );
958 i64 = (i_size * f);
960 msg_Warn( p_demux, "DEMUX_SET_BYTE_POSITION: %"PRId64, i64 );
961 if( av_seek_frame( p_sys->ic, -1, i64, AVSEEK_FLAG_BYTE ) < 0 )
962 return VLC_EGENERIC;
964 ResetTime( p_demux, -1 );
966 else
968 ResetTime( p_demux, i64 - i_start_time );
970 return VLC_SUCCESS;
972 case DEMUX_GET_LENGTH:
973 pi64 = va_arg( args, int64_t * );
974 if( p_sys->ic->duration != (int64_t)AV_NOPTS_VALUE )
975 *pi64 = p_sys->ic->duration * 1000000 / AV_TIME_BASE;
976 else
977 *pi64 = 0;
978 return VLC_SUCCESS;
980 case DEMUX_GET_TIME:
981 pi64 = va_arg( args, int64_t * );
982 *pi64 = p_sys->i_pcr;
983 return VLC_SUCCESS;
985 case DEMUX_SET_TIME:
987 i64 = va_arg( args, int64_t );
988 i64 = i64 *AV_TIME_BASE / 1000000 + i_start_time;
990 msg_Warn( p_demux, "DEMUX_SET_TIME: %"PRId64, i64 );
992 if( av_seek_frame( p_sys->ic, -1, i64, AVSEEK_FLAG_BACKWARD ) < 0 )
994 return VLC_EGENERIC;
996 ResetTime( p_demux, i64 - i_start_time );
997 return VLC_SUCCESS;
1000 case DEMUX_HAS_UNSUPPORTED_META:
1002 bool *pb_bool = va_arg( args, bool* );
1003 *pb_bool = true;
1004 return VLC_SUCCESS;
1008 case DEMUX_GET_META:
1010 static const char names[][10] = {
1011 [vlc_meta_Title] = "title",
1012 [vlc_meta_Artist] = "artist",
1013 [vlc_meta_Genre] = "genre",
1014 [vlc_meta_Copyright] = "copyright",
1015 [vlc_meta_Album] = "album",
1016 //[vlc_meta_TrackNumber] -- TODO: parse number/total value
1017 [vlc_meta_Description] = "comment",
1018 //[vlc_meta_Rating]
1019 [vlc_meta_Date] = "date",
1020 [vlc_meta_Setting] = "encoder",
1021 //[vlc_meta_URL]
1022 [vlc_meta_Language] = "language",
1023 //[vlc_meta_NowPlaying]
1024 [vlc_meta_Publisher] = "publisher",
1025 [vlc_meta_EncodedBy] = "encoded_by",
1026 //[vlc_meta_ArtworkURL]
1027 //[vlc_meta_TrackID]
1028 //[vlc_meta_TrackTotal]
1030 vlc_meta_t *p_meta = va_arg( args, vlc_meta_t * );
1031 AVDictionary *dict = p_sys->ic->metadata;
1033 for( unsigned i = 0; i < sizeof(names) / sizeof(*names); i++)
1035 if( !names[i][0] )
1036 continue;
1038 AVDictionaryEntry *e = av_dict_get( dict, names[i], NULL, 0 );
1039 if( e != NULL && e->value != NULL && IsUTF8(e->value) )
1040 vlc_meta_Set( p_meta, i, e->value );
1042 return VLC_SUCCESS;
1045 case DEMUX_GET_ATTACHMENTS:
1047 input_attachment_t ***ppp_attach =
1048 va_arg( args, input_attachment_t*** );
1049 int *pi_int = va_arg( args, int * );
1050 int i;
1052 if( p_sys->i_attachments <= 0 )
1053 return VLC_EGENERIC;
1055 *pi_int = p_sys->i_attachments;;
1056 *ppp_attach = xmalloc( sizeof(input_attachment_t*) * p_sys->i_attachments );
1057 for( i = 0; i < p_sys->i_attachments; i++ )
1058 (*ppp_attach)[i] = vlc_input_attachment_Duplicate( p_sys->attachments[i] );
1059 return VLC_SUCCESS;
1062 case DEMUX_GET_TITLE_INFO:
1064 input_title_t ***ppp_title = va_arg( args, input_title_t *** );
1065 int *pi_int = va_arg( args, int * );
1066 int *pi_title_offset = va_arg( args, int * );
1067 int *pi_seekpoint_offset = va_arg( args, int * );
1069 if( !p_sys->p_title )
1070 return VLC_EGENERIC;
1072 *pi_int = 1;
1073 *ppp_title = xmalloc( sizeof( input_title_t*) );
1074 (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->p_title );
1075 *pi_title_offset = 0;
1076 *pi_seekpoint_offset = 0;
1077 return VLC_SUCCESS;
1079 case DEMUX_SET_TITLE:
1081 const int i_title = va_arg( args, int );
1082 if( !p_sys->p_title || i_title != 0 )
1083 return VLC_EGENERIC;
1084 return VLC_SUCCESS;
1086 case DEMUX_SET_SEEKPOINT:
1088 const int i_seekpoint = va_arg( args, int );
1089 if( !p_sys->p_title )
1090 return VLC_EGENERIC;
1092 i64 = p_sys->p_title->seekpoint[i_seekpoint]->i_time_offset *
1093 AV_TIME_BASE / 1000000 + i_start_time;
1095 msg_Warn( p_demux, "DEMUX_SET_SEEKPOINT: %"PRId64, i64 );
1097 if( av_seek_frame( p_sys->ic, -1, i64, AVSEEK_FLAG_BACKWARD ) < 0 )
1099 return VLC_EGENERIC;
1101 ResetTime( p_demux, i64 - i_start_time );
1102 return VLC_SUCCESS;
1106 default:
1107 return VLC_EGENERIC;
1111 /*****************************************************************************
1112 * I/O wrappers for libavformat
1113 *****************************************************************************/
1114 static int IORead( void *opaque, uint8_t *buf, int buf_size )
1116 demux_t *p_demux = opaque;
1117 if( buf_size < 0 ) return -1;
1118 int i_ret = vlc_stream_Read( p_demux->s, buf, buf_size );
1119 return i_ret >= 0 ? i_ret : -1;
1122 static int64_t IOSeek( void *opaque, int64_t offset, int whence )
1124 demux_t *p_demux = opaque;
1125 int64_t i_absolute;
1126 int64_t i_size = stream_Size( p_demux->s );
1128 #ifdef AVFORMAT_DEBUG
1129 msg_Warn( p_demux, "IOSeek offset: %"PRId64", whence: %i", offset, whence );
1130 #endif
1132 switch( whence )
1134 #ifdef AVSEEK_SIZE
1135 case AVSEEK_SIZE:
1136 return i_size;
1137 #endif
1138 case SEEK_SET:
1139 i_absolute = (int64_t)offset;
1140 break;
1141 case SEEK_CUR:
1142 i_absolute = vlc_stream_Tell( p_demux->s ) + (int64_t)offset;
1143 break;
1144 case SEEK_END:
1145 i_absolute = i_size + (int64_t)offset;
1146 break;
1147 default:
1148 return -1;
1152 if( i_absolute < 0 )
1154 msg_Dbg( p_demux, "Trying to seek before the beginning" );
1155 return -1;
1158 if( i_size > 0 && i_absolute >= i_size )
1160 msg_Dbg( p_demux, "Trying to seek too far : EOF?" );
1161 return -1;
1164 if( vlc_stream_Seek( p_demux->s, i_absolute ) )
1166 msg_Warn( p_demux, "we were not allowed to seek, or EOF " );
1167 return -1;
1170 return vlc_stream_Tell( p_demux->s );