]> git.sesse.net Git - vlc/blob - modules/demux/avformat/demux.c
11bea18bb68cc8653a1d9a887391e666bbeaa48c
[vlc] / modules / demux / avformat / demux.c
1 /*****************************************************************************
2  * demux.c: demuxer using ffmpeg (libavformat).
3  *****************************************************************************
4  * Copyright (C) 2004-2007 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
38 /* ffmpeg header */
39 #if defined(HAVE_LIBAVFORMAT_AVFORMAT_H)
40 #   include <libavformat/avformat.h>
41 #elif defined(HAVE_FFMPEG_AVFORMAT_H)
42 #   include <ffmpeg/avformat.h>
43 #endif
44
45 #include "../../codec/avcodec/fourcc.h"
46 #include "../../codec/avcodec/chroma.h"
47 #include "avformat.h"
48
49 //#define AVFORMAT_DEBUG 1
50
51 /* Version checking */
52 #if defined(HAVE_FFMPEG_AVFORMAT_H) || defined(HAVE_LIBAVFORMAT_AVFORMAT_H)
53
54 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(50<<8)+0) )
55 #   define HAVE_FFMPEG_CODEC_ATTACHMENT 1
56 #endif
57
58 /*****************************************************************************
59  * demux_sys_t: demux descriptor
60  *****************************************************************************/
61 struct demux_sys_t
62 {
63     ByteIOContext   io;
64     int             io_buffer_size;
65     uint8_t        *io_buffer;
66
67     AVInputFormat  *fmt;
68     AVFormatContext *ic;
69     URLContext     url;
70     URLProtocol    prot;
71
72     int             i_tk;
73     es_out_id_t     **tk;
74
75     int64_t     i_pcr;
76     int64_t     i_pcr_inc;
77     int         i_pcr_tk;
78 };
79
80 /*****************************************************************************
81  * Local prototypes
82  *****************************************************************************/
83 static int Demux  ( demux_t *p_demux );
84 static int Control( demux_t *p_demux, int i_query, va_list args );
85
86 static int IORead( void *opaque, uint8_t *buf, int buf_size );
87 static offset_t IOSeek( void *opaque, offset_t offset, int whence );
88
89 /*****************************************************************************
90  * Open
91  *****************************************************************************/
92 int OpenDemux( vlc_object_t *p_this )
93 {
94     demux_t       *p_demux = (demux_t*)p_this;
95     demux_sys_t   *p_sys;
96     AVProbeData   pd;
97     AVInputFormat *fmt;
98     unsigned int i;
99     bool b_avfmt_nofile;
100
101     /* Init Probe data */
102     pd.filename = p_demux->psz_path;
103     if( ( pd.buf_size = stream_Peek( p_demux->s, &pd.buf, 2048 ) ) <= 0 )
104     {
105         msg_Warn( p_demux, "cannot peek" );
106         return VLC_EGENERIC;
107     }
108
109     av_register_all(); /* Can be called several times */
110
111     /* Guess format */
112     if( !( fmt = av_probe_input_format( &pd, 1 ) ) )
113     {
114         msg_Dbg( p_demux, "couldn't guess format" );
115         return VLC_EGENERIC;
116     }
117
118     /* Don't try to handle MPEG unless forced */
119     if( !p_demux->b_force &&
120         ( !strcmp( fmt->name, "mpeg" ) ||
121           !strcmp( fmt->name, "vcd" ) ||
122           !strcmp( fmt->name, "vob" ) ||
123           !strcmp( fmt->name, "mpegts" ) ||
124           /* libavformat's redirector won't work */
125           !strcmp( fmt->name, "redir" ) ||
126           !strcmp( fmt->name, "sdp" ) ) )
127     {
128         return VLC_EGENERIC;
129     }
130
131     /* Don't trigger false alarms on bin files */
132     if( !p_demux->b_force && !strcmp( fmt->name, "psxstr" ) )
133     {
134         int i_len;
135
136         if( !p_demux->psz_path ) return VLC_EGENERIC;
137
138         i_len = strlen( p_demux->psz_path );
139         if( i_len < 4 ) return VLC_EGENERIC;
140
141         if( strcasecmp( &p_demux->psz_path[i_len - 4], ".str" ) &&
142             strcasecmp( &p_demux->psz_path[i_len - 4], ".xai" ) &&
143             strcasecmp( &p_demux->psz_path[i_len - 3], ".xa" ) )
144         {
145             return VLC_EGENERIC;
146         }
147     }
148
149     msg_Dbg( p_demux, "detected format: %s", fmt->name );
150
151     /* Fill p_demux fields */
152     p_demux->pf_demux = Demux;
153     p_demux->pf_control = Control;
154     p_demux->p_sys = p_sys = malloc( sizeof( demux_sys_t ) );
155     p_sys->ic = 0;
156     p_sys->fmt = fmt;
157     p_sys->i_tk = 0;
158     p_sys->tk = NULL;
159     p_sys->i_pcr_tk = -1;
160     p_sys->i_pcr = -1;
161
162     /* Create I/O wrapper */
163     p_sys->io_buffer_size = 32768;  /* FIXME */
164     p_sys->io_buffer = malloc( p_sys->io_buffer_size );
165     p_sys->url.priv_data = p_demux;
166     p_sys->url.prot = &p_sys->prot;
167     p_sys->url.prot->name = "VLC I/O wrapper";
168     p_sys->url.prot->url_open = 0;
169     p_sys->url.prot->url_read =
170                     (int (*) (URLContext *, unsigned char *, int))IORead;
171     p_sys->url.prot->url_write = 0;
172     p_sys->url.prot->url_seek =
173                     (offset_t (*) (URLContext *, offset_t, int))IOSeek;
174     p_sys->url.prot->url_close = 0;
175     p_sys->url.prot->next = 0;
176     init_put_byte( &p_sys->io, p_sys->io_buffer, p_sys->io_buffer_size,
177                    0, &p_sys->url, IORead, NULL, IOSeek );
178
179     b_avfmt_nofile = p_sys->fmt->flags & AVFMT_NOFILE;
180     p_sys->fmt->flags |= AVFMT_NOFILE; /* libavformat must not fopen/fclose */
181
182     /* Open it */
183     if( av_open_input_stream( &p_sys->ic, &p_sys->io, p_demux->psz_path,
184                               p_sys->fmt, NULL ) )
185     {
186         msg_Err( p_demux, "av_open_input_stream failed" );
187         if( !b_avfmt_nofile ) p_sys->fmt->flags ^= AVFMT_NOFILE;
188         CloseDemux( p_this );
189         return VLC_EGENERIC;
190     }
191
192     if( av_find_stream_info( p_sys->ic ) < 0 )
193     {
194         msg_Err( p_demux, "av_find_stream_info failed" );
195         if( !b_avfmt_nofile ) p_sys->fmt->flags ^= AVFMT_NOFILE;
196         CloseDemux( p_this );
197         return VLC_EGENERIC;
198     }
199     if( !b_avfmt_nofile ) p_sys->fmt->flags ^= AVFMT_NOFILE;
200
201     for( i = 0; i < p_sys->ic->nb_streams; i++ )
202     {
203         AVCodecContext *cc = p_sys->ic->streams[i]->codec;
204         es_out_id_t  *es;
205         es_format_t  fmt;
206         vlc_fourcc_t fcc;
207         const char *psz_type = "unknown";
208
209         if( !GetVlcFourcc( cc->codec_id, NULL, &fcc, NULL ) )
210             fcc = VLC_FOURCC( 'u', 'n', 'd', 'f' );
211
212         switch( cc->codec_type )
213         {
214         case CODEC_TYPE_AUDIO:
215             es_format_Init( &fmt, AUDIO_ES, fcc );
216             fmt.audio.i_channels = cc->channels;
217             fmt.audio.i_rate = cc->sample_rate;
218 #if LIBAVCODEC_VERSION_INT < ((52<<16)+(0<<8)+0)
219             fmt.audio.i_bitspersample = cc->bits_per_sample;
220 #else
221             fmt.audio.i_bitspersample = cc->bits_per_coded_sample;
222 #endif
223             fmt.audio.i_blockalign = cc->block_align;
224             psz_type = "audio";
225             break;
226         case CODEC_TYPE_VIDEO:
227             es_format_Init( &fmt, VIDEO_ES, fcc );
228
229             /* Special case for raw video data */
230             if( cc->codec_id == CODEC_ID_RAWVIDEO )
231             {
232                 msg_Dbg( p_demux, "raw video, pixel format: %i", cc->pix_fmt );
233                 if( GetVlcChroma( &fmt.video, cc->pix_fmt ) != VLC_SUCCESS)
234                 {
235                     msg_Err( p_demux, "was unable to find a FourCC match for raw video" );
236                 }
237                 else
238                     fmt.i_codec = fmt.video.i_chroma;
239             }
240
241             fmt.video.i_width = cc->width;
242             fmt.video.i_height = cc->height;
243             if( cc->palctrl )
244             {
245                 fmt.video.p_palette = malloc( sizeof(video_palette_t) );
246                 *fmt.video.p_palette = *(video_palette_t *)cc->palctrl;
247             }
248             psz_type = "video";
249             break;
250         case CODEC_TYPE_SUBTITLE:
251             es_format_Init( &fmt, SPU_ES, fcc );
252             psz_type = "subtitle";
253             break;
254
255         default:
256             es_format_Init( &fmt, UNKNOWN_ES, 0 );
257             if( cc->codec_type == CODEC_TYPE_DATA )
258                 psz_type = "data";
259 #ifdef HAVE_FFMPEG_CODEC_ATTACHMENT
260             else if( cc->codec_type == CODEC_TYPE_ATTACHMENT )
261                 psz_type = "attachment";
262 #endif
263             msg_Warn( p_demux, "unsupported track type in ffmpeg demux" );
264             break;
265         }
266
267         fmt.psz_language = strdup( p_sys->ic->streams[i]->language );
268         fmt.i_extra = cc->extradata_size;
269         fmt.p_extra = cc->extradata;
270         es = es_out_Add( p_demux->out, &fmt );
271
272         msg_Dbg( p_demux, "adding es: %s codec = %4.4s",
273                  psz_type, (char*)&fcc );
274         TAB_APPEND( p_sys->i_tk, p_sys->tk, es );
275     }
276
277     msg_Dbg( p_demux, "AVFormat supported stream" );
278     msg_Dbg( p_demux, "    - format = %s (%s)",
279              p_sys->fmt->name, p_sys->fmt->long_name );
280     msg_Dbg( p_demux, "    - start time = %"PRId64,
281              ( p_sys->ic->start_time != (int64_t)AV_NOPTS_VALUE ) ?
282              p_sys->ic->start_time * 1000000 / AV_TIME_BASE : -1 );
283     msg_Dbg( p_demux, "    - duration = %"PRId64,
284              ( p_sys->ic->duration != (int64_t)AV_NOPTS_VALUE ) ?
285              p_sys->ic->duration * 1000000 / AV_TIME_BASE : -1 );
286
287     return VLC_SUCCESS;
288 }
289
290 /*****************************************************************************
291  * Close
292  *****************************************************************************/
293 void CloseDemux( vlc_object_t *p_this )
294 {
295     demux_t     *p_demux = (demux_t*)p_this;
296     demux_sys_t *p_sys = p_demux->p_sys;
297     bool b_avfmt_nofile;
298
299     FREENULL( p_sys->tk );
300
301     b_avfmt_nofile = p_sys->fmt->flags & AVFMT_NOFILE;
302     p_sys->fmt->flags |= AVFMT_NOFILE; /* libavformat must not fopen/fclose */
303     if( p_sys->ic ) av_close_input_file( p_sys->ic );
304     if( !b_avfmt_nofile ) p_sys->fmt->flags ^= AVFMT_NOFILE;
305
306     free( p_sys->io_buffer );
307     free( p_sys );
308 }
309
310 /*****************************************************************************
311  * Demux:
312  *****************************************************************************/
313 static int Demux( demux_t *p_demux )
314 {
315     demux_sys_t *p_sys = p_demux->p_sys;
316     AVPacket    pkt;
317     block_t     *p_frame;
318     int64_t     i_start_time;
319
320     /* Read a frame */
321     if( av_read_frame( p_sys->ic, &pkt ) )
322     {
323         return 0;
324     }
325     if( pkt.stream_index < 0 || pkt.stream_index >= p_sys->i_tk )
326     {
327         av_free_packet( &pkt );
328         return 1;
329     }
330     if( ( p_frame = block_New( p_demux, pkt.size ) ) == NULL )
331     {
332         return 0;
333     }
334
335     memcpy( p_frame->p_buffer, pkt.data, pkt.size );
336
337     if( pkt.flags & PKT_FLAG_KEY )
338         p_frame->i_flags |= BLOCK_FLAG_TYPE_I;
339
340     i_start_time = ( p_sys->ic->start_time != (int64_t)AV_NOPTS_VALUE ) ?
341         ( p_sys->ic->start_time * 1000000 / AV_TIME_BASE )  : 0;
342
343     p_frame->i_dts = ( pkt.dts == (int64_t)AV_NOPTS_VALUE ) ?
344         0 : (pkt.dts) * 1000000 *
345         p_sys->ic->streams[pkt.stream_index]->time_base.num /
346         p_sys->ic->streams[pkt.stream_index]->time_base.den - i_start_time;
347     p_frame->i_pts = ( pkt.pts == (int64_t)AV_NOPTS_VALUE ) ?
348         0 : (pkt.pts) * 1000000 *
349         p_sys->ic->streams[pkt.stream_index]->time_base.num /
350         p_sys->ic->streams[pkt.stream_index]->time_base.den - i_start_time;
351
352 #ifdef AVFORMAT_DEBUG
353     msg_Dbg( p_demux, "tk[%d] dts=%"PRId64" pts=%"PRId64,
354              pkt.stream_index, p_frame->i_dts, p_frame->i_pts );
355 #endif
356
357     if( pkt.dts > 0  &&
358         ( pkt.stream_index == p_sys->i_pcr_tk || p_sys->i_pcr_tk < 0 ) )
359     {
360         p_sys->i_pcr_tk = pkt.stream_index;
361         p_sys->i_pcr = p_frame->i_dts;
362
363         es_out_Control( p_demux->out, ES_OUT_SET_PCR, (int64_t)p_sys->i_pcr );
364     }
365
366     es_out_Send( p_demux->out, p_sys->tk[pkt.stream_index], p_frame );
367     av_free_packet( &pkt );
368     return 1;
369 }
370
371 /*****************************************************************************
372  * Control:
373  *****************************************************************************/
374 static int Control( demux_t *p_demux, int i_query, va_list args )
375 {
376     demux_sys_t *p_sys = p_demux->p_sys;
377     double f, *pf;
378     int64_t i64, *pi64;
379
380     switch( i_query )
381     {
382         case DEMUX_GET_POSITION:
383             pf = (double*) va_arg( args, double* ); *pf = 0.0;
384             i64 = stream_Size( p_demux->s );
385             if( i64 > 0 )
386             {
387                 *pf = (double)stream_Tell( p_demux->s ) / (double)i64;
388             }
389
390             if( (p_sys->ic->duration != (int64_t)AV_NOPTS_VALUE) && (p_sys->i_pcr > 0) )
391             {
392                 *pf = (double)p_sys->i_pcr / (double)p_sys->ic->duration;
393             }
394
395             return VLC_SUCCESS;
396
397         case DEMUX_SET_POSITION:
398             f = (double) va_arg( args, double );
399             i64 = stream_Tell( p_demux->s );
400             if( p_sys->i_pcr > 0 )
401             {
402                 i64 = p_sys->ic->duration * f;
403                 if( p_sys->ic->start_time != (int64_t)AV_NOPTS_VALUE )
404                     i64 += p_sys->ic->start_time;
405
406                 msg_Warn( p_demux, "DEMUX_SET_POSITION: %"PRId64, i64 );
407
408                 /* If we have a duration, we prefer to seek by time
409                    but if we don't, or if the seek fails, try BYTE seeking */
410                 if( p_sys->ic->duration == (int64_t)AV_NOPTS_VALUE ||
411                     (av_seek_frame( p_sys->ic, -1, i64, 0 ) < 0) )
412                 {
413                     int64_t i_size = stream_Size( p_demux->s );
414                     i64 = (int64_t)i_size * f;
415
416                     msg_Warn( p_demux, "DEMUX_SET_BYTE_POSITION: %"PRId64, i64 );
417                     if( av_seek_frame( p_sys->ic, -1, i64, AVSEEK_FLAG_BYTE ) < 0 )
418                         return VLC_EGENERIC;
419                 }
420                 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
421                 p_sys->i_pcr = -1; /* Invalidate time display */
422             }
423             return VLC_SUCCESS;
424
425         case DEMUX_GET_LENGTH:
426             pi64 = (int64_t*)va_arg( args, int64_t * );
427             if( p_sys->ic->duration != (int64_t)AV_NOPTS_VALUE )
428             {
429                 *pi64 = p_sys->ic->duration;
430             }
431             else *pi64 = 0;
432             return VLC_SUCCESS;
433
434         case DEMUX_GET_TIME:
435             pi64 = (int64_t*)va_arg( args, int64_t * );
436             *pi64 = p_sys->i_pcr;
437             return VLC_SUCCESS;
438
439         case DEMUX_SET_TIME:
440             i64 = (int64_t)va_arg( args, int64_t );
441             i64 = i64 *AV_TIME_BASE / 1000000;
442             if( p_sys->ic->start_time != (int64_t)AV_NOPTS_VALUE )
443                 i64 += p_sys->ic->start_time;
444
445             msg_Warn( p_demux, "DEMUX_SET_TIME: %"PRId64, i64 );
446
447             if( av_seek_frame( p_sys->ic, -1, i64, 0 ) < 0 )
448             {
449                 return VLC_EGENERIC;
450             }
451             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
452             p_sys->i_pcr = -1; /* Invalidate time display */
453             return VLC_SUCCESS;
454
455         case DEMUX_GET_META:
456         {
457             vlc_meta_t *p_meta = (vlc_meta_t*)va_arg( args, vlc_meta_t* );
458
459             if( !p_sys->ic->title[0] || !p_sys->ic->author[0] ||
460                 !p_sys->ic->copyright[0] || !p_sys->ic->comment[0] ||
461                 /*!p_sys->ic->album[0] ||*/ !p_sys->ic->genre[0] )
462             {
463                 return VLC_EGENERIC;
464             }
465
466             if( p_sys->ic->title[0] )
467                 vlc_meta_SetTitle( p_meta, p_sys->ic->title );
468             if( p_sys->ic->author[0] )
469                 vlc_meta_SetArtist( p_meta, p_sys->ic->author );
470             if( p_sys->ic->copyright[0] )
471                 vlc_meta_SetCopyright( p_meta, p_sys->ic->copyright );
472             if( p_sys->ic->comment[0] )
473                 vlc_meta_SetDescription( p_meta, p_sys->ic->comment );
474             if( p_sys->ic->genre[0] )
475                 vlc_meta_SetGenre( p_meta, p_sys->ic->genre );
476             return VLC_SUCCESS;
477         }
478
479         default:
480             return VLC_EGENERIC;
481     }
482 }
483
484 /*****************************************************************************
485  * I/O wrappers for libavformat
486  *****************************************************************************/
487 static int IORead( void *opaque, uint8_t *buf, int buf_size )
488 {
489     URLContext *p_url = opaque;
490     demux_t *p_demux = p_url->priv_data;
491     if( buf_size < 0 ) return -1;
492     int i_ret = stream_Read( p_demux->s, buf, buf_size );
493     return i_ret ? i_ret : -1;
494 }
495
496 static offset_t IOSeek( void *opaque, offset_t offset, int whence )
497 {
498     URLContext *p_url = opaque;
499     demux_t *p_demux = p_url->priv_data;
500     int64_t i_absolute = (int64_t)offset;
501     int64_t i_size = stream_Size( p_demux->s );
502
503 #ifdef AVFORMAT_DEBUG
504     msg_Warn( p_demux, "IOSeek offset: %"PRId64", whence: %i", offset, whence );
505 #endif
506
507     switch( whence )
508     {
509 #ifdef AVSEEK_SIZE
510         case AVSEEK_SIZE:
511             return i_size;
512 #endif
513         case SEEK_SET:
514             i_absolute = (int64_t)offset;
515             break;
516         case SEEK_CUR:
517             i_absolute = stream_Tell( p_demux->s ) + (int64_t)offset;
518             break;
519         case SEEK_END:
520             i_absolute = i_size + (int64_t)offset;
521             break;
522         default:
523             return -1;
524
525     }
526     if( i_absolute < 0 )
527         i_absolute = 0;
528
529     if( i_size > 0 && i_absolute >= i_size )
530     {
531         msg_Dbg( p_demux, "Trying to seek too far : EOF?" );
532         return -1;
533     }
534
535     if( stream_Seek( p_demux->s, i_absolute ) )
536     {
537         msg_Warn( p_demux, "we were not allowed to seek, or EOF " );
538         return -1;
539     }
540
541     return stream_Tell( p_demux->s );
542 }
543
544 #endif /* HAVE_LIBAVFORMAT_AVFORMAT_H */