find_subfiles: select subtitle files matching -slang
[mplayer/greg.git] / libmpdemux / demux_lavf.c
blob3aca4b603cc8a093e1dc9f02d3d1e6ffb735a1d5
1 /*
2 * Copyright (C) 2004 Michael Niedermayer <michaelni@gmx.at>
4 * This file is part of MPlayer.
6 * MPlayer is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * MPlayer is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with MPlayer; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 // #include <stdio.h>
22 #include <stdlib.h>
23 // #include <unistd.h>
24 #include <limits.h>
25 #include <stdbool.h>
26 #include <string.h>
28 #include "config.h"
29 #include "options.h"
30 #include "mp_msg.h"
31 #include "av_opts.h"
32 #include "bstr.h"
34 #include "stream/stream.h"
35 #include "aviprint.h"
36 #include "demuxer.h"
37 #include "stheader.h"
38 #include "m_option.h"
39 #include "sub/sub.h"
41 #include "libavformat/avformat.h"
42 #include "libavformat/avio.h"
43 #include "libavutil/avutil.h"
44 #include "libavutil/avstring.h"
45 #include "libavcodec/opt.h"
47 #include "mp_taglists.h"
49 #define INITIAL_PROBE_SIZE STREAM_BUFFER_SIZE
50 #define SMALL_MAX_PROBE_SIZE (32 * 1024)
51 #define PROBE_BUF_SIZE (2*1024*1024)
53 const m_option_t lavfdopts_conf[] = {
54 OPT_INTRANGE("probesize", lavfdopts.probesize, 0, 32, INT_MAX),
55 OPT_STRING("format", lavfdopts.format, 0),
56 OPT_INTRANGE("analyzeduration", lavfdopts.analyzeduration, 0, 0, INT_MAX),
57 OPT_STRING("cryptokey", lavfdopts.cryptokey, 0),
58 OPT_STRING("o", lavfdopts.avopt, 0),
59 {NULL, NULL, 0, 0, 0, 0, NULL}
62 #define BIO_BUFFER_SIZE 32768
64 typedef struct lavf_priv {
65 AVInputFormat *avif;
66 AVFormatContext *avfc;
67 ByteIOContext *pb;
68 uint8_t buffer[BIO_BUFFER_SIZE];
69 int audio_streams;
70 int video_streams;
71 int sub_streams;
72 int64_t last_pts;
73 int astreams[MAX_A_STREAMS];
74 int vstreams[MAX_V_STREAMS];
75 int sstreams[MAX_S_STREAMS];
76 int cur_program;
77 int nb_streams_last;
78 bool internet_radio_hack;
79 bool use_dts;
80 bool seek_by_bytes;
81 int bitrate;
82 }lavf_priv_t;
84 static int mp_read(void *opaque, uint8_t *buf, int size) {
85 struct demuxer *demuxer = opaque;
86 struct stream *stream = demuxer->stream;
87 int ret;
89 ret=stream_read(stream, buf, size);
91 mp_msg(MSGT_HEADER,MSGL_DBG2,"%d=mp_read(%p, %p, %d), pos: %"PRId64", eof:%d\n",
92 ret, stream, buf, size, stream_tell(stream), stream->eof);
93 return ret;
96 static int64_t mp_seek(void *opaque, int64_t pos, int whence) {
97 struct demuxer *demuxer = opaque;
98 struct stream *stream = demuxer->stream;
99 int64_t current_pos;
100 mp_msg(MSGT_HEADER,MSGL_DBG2,"mp_seek(%p, %"PRId64", %d)\n", stream, pos, whence);
101 if(whence == SEEK_CUR)
102 pos +=stream_tell(stream);
103 else if(whence == SEEK_END && stream->end_pos > 0)
104 pos += stream->end_pos;
105 else if(whence == SEEK_SET)
106 pos += stream->start_pos;
107 else if(whence == AVSEEK_SIZE && stream->end_pos > 0)
108 return stream->end_pos - stream->start_pos;
109 else
110 return -1;
112 if(pos<0)
113 return -1;
114 current_pos = stream_tell(stream);
115 if(stream_seek(stream, pos)==0) {
116 stream_reset(stream);
117 stream_seek(stream, current_pos);
118 return -1;
121 return pos - stream->start_pos;
124 static int64_t mp_read_seek(void *opaque, int stream_idx, int64_t ts, int flags)
126 struct demuxer *demuxer = opaque;
127 struct stream *stream = demuxer->stream;
128 struct lavf_priv *priv = demuxer->priv;
130 AVStream *st = priv->avfc->streams[stream_idx];
131 double pts = (double)ts * st->time_base.num / st->time_base.den;
132 int ret = stream_control(stream, STREAM_CTRL_SEEK_TO_TIME, &pts);
133 if (ret < 0)
134 ret = AVERROR(ENOSYS);
135 return ret;
138 static void list_formats(void) {
139 mp_msg(MSGT_DEMUX, MSGL_INFO, "Available lavf input formats:\n");
140 AVInputFormat *fmt = NULL;
141 while (fmt = av_iformat_next(fmt))
142 mp_msg(MSGT_DEMUX, MSGL_INFO, "%15s : %s\n", fmt->name, fmt->long_name);
145 static int lavf_check_file(demuxer_t *demuxer){
146 struct MPOpts *opts = demuxer->opts;
147 struct lavfdopts *lavfdopts = &opts->lavfdopts;
148 AVProbeData avpd;
149 lavf_priv_t *priv;
150 int probe_data_size = 0;
151 int read_size = INITIAL_PROBE_SIZE;
152 int score;
154 if(!demuxer->priv)
155 demuxer->priv=calloc(sizeof(lavf_priv_t),1);
156 priv= demuxer->priv;
158 av_register_all();
160 char *format = lavfdopts->format;
161 if (!format)
162 format = demuxer->stream->lavf_type;
163 if (format) {
164 if (strcmp(format, "help") == 0) {
165 list_formats();
166 return 0;
168 priv->avif = av_find_input_format(format);
169 if (!priv->avif) {
170 mp_msg(MSGT_DEMUX, MSGL_FATAL, "Unknown lavf format %s\n", format);
171 return 0;
173 mp_msg(MSGT_DEMUX,MSGL_INFO,"Forced lavf %s demuxer\n", priv->avif->long_name);
174 return DEMUXER_TYPE_LAVF;
177 avpd.buf = av_mallocz(FFMAX(BIO_BUFFER_SIZE, PROBE_BUF_SIZE) +
178 FF_INPUT_BUFFER_PADDING_SIZE);
179 do {
180 read_size = stream_read(demuxer->stream, avpd.buf + probe_data_size, read_size);
181 if(read_size < 0) {
182 av_free(avpd.buf);
183 return 0;
185 probe_data_size += read_size;
186 avpd.filename= demuxer->stream->url;
187 if (!avpd.filename) {
188 mp_msg(MSGT_DEMUX, MSGL_WARN, "Stream url is not set!\n");
189 avpd.filename = "";
191 if (!strncmp(avpd.filename, "ffmpeg://", 9))
192 avpd.filename += 9;
193 avpd.buf_size= probe_data_size;
195 score = 0;
196 priv->avif= av_probe_input_format2(&avpd, probe_data_size > 0, &score);
197 read_size = FFMIN(2*read_size, PROBE_BUF_SIZE - probe_data_size);
198 } while ((demuxer->desc->type != DEMUXER_TYPE_LAVF_PREFERRED ||
199 probe_data_size < SMALL_MAX_PROBE_SIZE) &&
200 score <= AVPROBE_SCORE_MAX / 4 &&
201 read_size > 0 && probe_data_size < PROBE_BUF_SIZE);
202 av_free(avpd.buf);
204 if (!priv->avif || score <= AVPROBE_SCORE_MAX / 4) {
205 mp_msg(MSGT_HEADER,MSGL_V,"LAVF_check: no clue about this gibberish!\n");
206 return 0;
207 }else
208 mp_msg(MSGT_HEADER,MSGL_V,"LAVF_check: %s\n", priv->avif->long_name);
210 demuxer->filetype = priv->avif->long_name;
211 if (!demuxer->filetype)
212 demuxer->filetype = priv->avif->name;
214 return DEMUXER_TYPE_LAVF;
217 static bool matches_avinputformat_name(struct lavf_priv *priv,
218 const char *name)
220 const char *avifname = priv->avif->name;
221 while (1) {
222 const char *next = strchr(avifname, ',');
223 if (!next)
224 return !strcmp(avifname, name);
225 int len = next - avifname;
226 if (len == strlen(name) && !memcmp(avifname, name, len))
227 return true;
228 avifname = next + 1;
232 /* formats for which an internal demuxer is preferred */
233 static const char * const preferred_internal[] = {
234 /* lavf Matroska demuxer doesn't support ordered chapters and fails
235 * for more files */
236 "matroska",
237 #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(52, 99, 0)
238 /* Seeking doesn't work with lavf FLAC demuxer in FFmpeg versions
239 * without a FLAC parser. In principle this could use a runtime check to
240 * switch if a shared library is updated. */
241 "flac",
242 #endif
243 /* lavf gives neither pts nor dts for some video frames in .rm */
244 "rm",
245 NULL
248 static int lavf_check_preferred_file(demuxer_t *demuxer){
249 if (lavf_check_file(demuxer)) {
250 const char * const *p;
251 lavf_priv_t *priv = demuxer->priv;
252 for (p = preferred_internal; *p; p++)
253 if (matches_avinputformat_name(priv, *p))
254 return 0;
255 return DEMUXER_TYPE_LAVF_PREFERRED;
257 return 0;
260 static uint8_t char2int(char c) {
261 if (c >= '0' && c <= '9') return c - '0';
262 if (c >= 'a' && c <= 'f') return c - 'a' + 10;
263 if (c >= 'A' && c <= 'F') return c - 'A' + 10;
264 return 0;
267 static void parse_cryptokey(AVFormatContext *avfc, const char *str) {
268 int len = strlen(str) / 2;
269 uint8_t *key = av_mallocz(len);
270 int i;
271 avfc->keylen = len;
272 avfc->key = key;
273 for (i = 0; i < len; i++, str += 2)
274 *key++ = (char2int(str[0]) << 4) | char2int(str[1]);
277 static void handle_stream(demuxer_t *demuxer, AVFormatContext *avfc, int i) {
278 lavf_priv_t *priv= demuxer->priv;
279 AVStream *st= avfc->streams[i];
280 AVCodecContext *codec= st->codec;
281 char *stream_type = NULL;
282 int stream_id;
283 AVMetadataTag *lang = av_metadata_get(st->metadata, "language", NULL, 0);
284 AVMetadataTag *title= av_metadata_get(st->metadata, "title", NULL, 0);
285 int g, override_tag = mp_av_codec_get_tag(mp_codecid_override_taglists,
286 codec->codec_id);
287 // For some formats (like PCM) always trust CODEC_ID_* more than codec_tag
288 if (override_tag)
289 codec->codec_tag = override_tag;
291 switch(codec->codec_type){
292 case CODEC_TYPE_AUDIO:{
293 WAVEFORMATEX *wf;
294 sh_audio_t* sh_audio;
295 sh_audio = new_sh_audio_aid(demuxer, i, priv->audio_streams);
296 if(!sh_audio)
297 break;
298 stream_type = "audio";
299 priv->astreams[priv->audio_streams] = i;
300 wf= calloc(sizeof(*wf) + codec->extradata_size, 1);
301 // mp4a tag is used for all mp4 files no matter what they actually contain
302 if(codec->codec_tag == MKTAG('m', 'p', '4', 'a'))
303 codec->codec_tag= 0;
304 if(!codec->codec_tag)
305 codec->codec_tag= mp_av_codec_get_tag(mp_wav_taglists, codec->codec_id);
306 wf->wFormatTag= codec->codec_tag;
307 wf->nChannels= codec->channels;
308 wf->nSamplesPerSec= codec->sample_rate;
309 wf->nAvgBytesPerSec= codec->bit_rate/8;
310 wf->nBlockAlign= codec->block_align ? codec->block_align : 1;
311 wf->wBitsPerSample= codec->bits_per_coded_sample;
312 wf->cbSize= codec->extradata_size;
313 if(codec->extradata_size)
314 memcpy(wf + 1, codec->extradata, codec->extradata_size);
315 sh_audio->wf= wf;
316 sh_audio->audio.dwSampleSize= codec->block_align;
317 if(codec->frame_size && codec->sample_rate){
318 sh_audio->audio.dwScale=codec->frame_size;
319 sh_audio->audio.dwRate= codec->sample_rate;
320 }else{
321 sh_audio->audio.dwScale= codec->block_align ? codec->block_align*8 : 8;
322 sh_audio->audio.dwRate = codec->bit_rate;
324 g= av_gcd(sh_audio->audio.dwScale, sh_audio->audio.dwRate);
325 sh_audio->audio.dwScale /= g;
326 sh_audio->audio.dwRate /= g;
327 // printf("sca:%d rat:%d fs:%d sr:%d ba:%d\n", sh_audio->audio.dwScale, sh_audio->audio.dwRate, codec->frame_size, codec->sample_rate, codec->block_align);
328 sh_audio->ds= demuxer->audio;
329 sh_audio->format= codec->codec_tag;
330 sh_audio->channels= codec->channels;
331 sh_audio->samplerate= codec->sample_rate;
332 sh_audio->i_bps= codec->bit_rate/8;
333 switch (codec->codec_id) {
334 case CODEC_ID_PCM_S8:
335 case CODEC_ID_PCM_U8:
336 sh_audio->samplesize = 1;
337 break;
338 case CODEC_ID_PCM_S16LE:
339 case CODEC_ID_PCM_S16BE:
340 case CODEC_ID_PCM_U16LE:
341 case CODEC_ID_PCM_U16BE:
342 sh_audio->samplesize = 2;
343 break;
344 case CODEC_ID_PCM_ALAW:
345 sh_audio->format = 0x6;
346 break;
347 case CODEC_ID_PCM_MULAW:
348 sh_audio->format = 0x7;
349 break;
351 if (title && title->value)
352 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AID_%d_NAME=%s\n", priv->audio_streams, title->value);
353 if (lang && lang->value) {
354 sh_audio->lang = strdup(lang->value);
355 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AID_%d_LANG=%s\n", priv->audio_streams, sh_audio->lang);
357 if (st->disposition & AV_DISPOSITION_DEFAULT)
358 sh_audio->default_track = 1;
359 if(mp_msg_test(MSGT_HEADER,MSGL_V) ) print_wave_header(sh_audio->wf, MSGL_V);
360 st->discard= AVDISCARD_ALL;
361 stream_id = priv->audio_streams++;
362 break;
364 case CODEC_TYPE_VIDEO:{
365 sh_video_t* sh_video;
366 BITMAPINFOHEADER *bih;
367 sh_video=new_sh_video_vid(demuxer, i, priv->video_streams);
368 if(!sh_video) break;
369 stream_type = "video";
370 priv->vstreams[priv->video_streams] = i;
371 bih=calloc(sizeof(*bih) + codec->extradata_size,1);
373 if(codec->codec_id == CODEC_ID_RAWVIDEO) {
374 switch (codec->pix_fmt) {
375 case PIX_FMT_RGB24:
376 codec->codec_tag= MKTAG(24, 'B', 'G', 'R');
377 case PIX_FMT_BGR24:
378 codec->codec_tag= MKTAG(24, 'R', 'G', 'B');
381 if(!codec->codec_tag)
382 codec->codec_tag= mp_av_codec_get_tag(mp_bmp_taglists, codec->codec_id);
383 bih->biSize= sizeof(*bih) + codec->extradata_size;
384 bih->biWidth= codec->width;
385 bih->biHeight= codec->height;
386 bih->biBitCount= codec->bits_per_coded_sample;
387 bih->biSizeImage = bih->biWidth * bih->biHeight * bih->biBitCount/8;
388 bih->biCompression= codec->codec_tag;
389 sh_video->bih= bih;
390 sh_video->disp_w= codec->width;
391 sh_video->disp_h= codec->height;
392 if (st->time_base.den) { /* if container has time_base, use that */
393 sh_video->video.dwRate= st->time_base.den;
394 sh_video->video.dwScale= st->time_base.num;
395 } else {
396 sh_video->video.dwRate= codec->time_base.den;
397 sh_video->video.dwScale= codec->time_base.num;
399 sh_video->fps=av_q2d(st->r_frame_rate);
400 sh_video->frametime=1/av_q2d(st->r_frame_rate);
401 sh_video->format=bih->biCompression;
402 if(st->sample_aspect_ratio.num)
403 sh_video->aspect = codec->width * st->sample_aspect_ratio.num
404 / (float)(codec->height * st->sample_aspect_ratio.den);
405 else
406 sh_video->aspect=codec->width * codec->sample_aspect_ratio.num
407 / (float)(codec->height * codec->sample_aspect_ratio.den);
408 sh_video->i_bps=codec->bit_rate/8;
409 if (title && title->value)
410 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VID_%d_NAME=%s\n", priv->video_streams, title->value);
411 mp_msg(MSGT_DEMUX,MSGL_DBG2,"aspect= %d*%d/(%d*%d)\n",
412 codec->width, codec->sample_aspect_ratio.num,
413 codec->height, codec->sample_aspect_ratio.den);
415 sh_video->ds= demuxer->video;
416 if(codec->extradata_size)
417 memcpy(sh_video->bih + 1, codec->extradata, codec->extradata_size);
418 if( mp_msg_test(MSGT_HEADER,MSGL_V) ) print_video_header(sh_video->bih, MSGL_V);
420 short biPlanes;
421 int biXPelsPerMeter;
422 int biYPelsPerMeter;
423 int biClrUsed;
424 int biClrImportant;
426 if(demuxer->video->id != priv->video_streams
427 && demuxer->video->id != -1)
428 st->discard= AVDISCARD_ALL;
429 else{
430 demuxer->video->id = i;
431 demuxer->video->sh= demuxer->v_streams[i];
433 stream_id = priv->video_streams++;
434 break;
436 case CODEC_TYPE_SUBTITLE:{
437 sh_sub_t* sh_sub;
438 char type;
439 /* only support text subtitles for now */
440 if(codec->codec_id == CODEC_ID_TEXT)
441 type = 't';
442 else if(codec->codec_id == CODEC_ID_MOV_TEXT)
443 type = 'm';
444 else if(codec->codec_id == CODEC_ID_SSA)
445 type = 'a';
446 else if(codec->codec_id == CODEC_ID_DVD_SUBTITLE)
447 type = 'v';
448 else if(codec->codec_id == CODEC_ID_XSUB)
449 type = 'x';
450 else if(codec->codec_id == CODEC_ID_DVB_SUBTITLE)
451 type = 'b';
452 else if(codec->codec_id == CODEC_ID_DVB_TELETEXT)
453 type = 'd';
454 else if(codec->codec_id == CODEC_ID_HDMV_PGS_SUBTITLE)
455 type = 'p';
456 else
457 break;
458 sh_sub = new_sh_sub_sid(demuxer, i, priv->sub_streams);
459 if(!sh_sub) break;
460 stream_type = "subtitle";
461 priv->sstreams[priv->sub_streams] = i;
462 sh_sub->type = type;
463 if (codec->extradata_size) {
464 sh_sub->extradata = malloc(codec->extradata_size);
465 memcpy(sh_sub->extradata, codec->extradata, codec->extradata_size);
466 sh_sub->extradata_len = codec->extradata_size;
468 if (title && title->value)
469 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SID_%d_NAME=%s\n", priv->sub_streams, title->value);
470 if (lang && lang->value) {
471 sh_sub->lang = strdup(lang->value);
472 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SID_%d_LANG=%s\n", priv->sub_streams, sh_sub->lang);
474 if (st->disposition & AV_DISPOSITION_DEFAULT)
475 sh_sub->default_track = 1;
476 stream_id = priv->sub_streams++;
477 break;
479 case CODEC_TYPE_ATTACHMENT:{
480 if (st->codec->codec_id == CODEC_ID_TTF)
481 demuxer_add_attachment(demuxer, BSTR(st->filename),
482 BSTR("application/x-truetype-font"),
483 (struct bstr){codec->extradata,
484 codec->extradata_size});
485 break;
487 default:
488 st->discard= AVDISCARD_ALL;
490 if (stream_type) {
491 AVCodec *avc = avcodec_find_decoder(codec->codec_id);
492 const char *codec_name = avc ? avc->name : "unknown";
493 if (!avc && *stream_type == 's' && demuxer->s_streams[stream_id])
494 codec_name = sh_sub_type2str(((sh_sub_t *)demuxer->s_streams[stream_id])->type);
495 mp_msg(MSGT_DEMUX, MSGL_INFO, "[lavf] stream %d: %s (%s), -%cid %d", i, stream_type, codec_name, *stream_type, stream_id);
496 if (lang && lang->value && *stream_type != 'v')
497 mp_msg(MSGT_DEMUX, MSGL_INFO, ", -%clang %s", *stream_type, lang->value);
498 if (title && title->value)
499 mp_msg(MSGT_DEMUX, MSGL_INFO, ", %s", title->value);
500 mp_msg(MSGT_DEMUX, MSGL_INFO, "\n");
504 static demuxer_t* demux_open_lavf(demuxer_t *demuxer){
505 struct MPOpts *opts = demuxer->opts;
506 struct lavfdopts *lavfdopts = &opts->lavfdopts;
507 AVFormatContext *avfc;
508 AVFormatParameters ap;
509 const AVOption *opt;
510 AVMetadataTag *t = NULL;
511 lavf_priv_t *priv= demuxer->priv;
512 int i;
513 char mp_filename[256]="mp:";
515 memset(&ap, 0, sizeof(AVFormatParameters));
517 stream_seek(demuxer->stream, 0);
519 avfc = avformat_alloc_context();
521 if (lavfdopts->cryptokey)
522 parse_cryptokey(avfc, lavfdopts->cryptokey);
523 if (matches_avinputformat_name(priv, "avi")) {
524 /* for avi libavformat returns the avi timestamps in .dts,
525 * some made-up stuff that's not really pts in .pts */
526 priv->use_dts = true;
527 demuxer->timestamp_type = TIMESTAMP_TYPE_SORT;
528 } else {
529 if (opts->user_correct_pts != 0)
530 avfc->flags |= AVFMT_FLAG_GENPTS;
532 if (index_mode == 0)
533 avfc->flags |= AVFMT_FLAG_IGNIDX;
535 ap.prealloced_context = 1;
536 if (lavfdopts->probesize) {
537 opt = av_set_int(avfc, "probesize", lavfdopts->probesize);
538 if(!opt) mp_msg(MSGT_HEADER,MSGL_ERR, "demux_lavf, couldn't set option probesize to %u\n", lavfdopts->probesize);
540 if (lavfdopts->analyzeduration) {
541 opt = av_set_int(avfc, "analyzeduration",
542 lavfdopts->analyzeduration * AV_TIME_BASE);
543 if (!opt)
544 mp_msg(MSGT_HEADER, MSGL_ERR, "demux_lavf, couldn't set option "
545 "analyzeduration to %u\n", lavfdopts->analyzeduration);
548 if (lavfdopts->avopt){
549 if(parse_avopts(avfc, lavfdopts->avopt) < 0){
550 mp_msg(MSGT_HEADER,MSGL_ERR, "Your options /%s/ look like gibberish to me pal\n", lavfdopts->avopt);
551 return NULL;
555 if(demuxer->stream->url) {
556 if (!strncmp(demuxer->stream->url, "ffmpeg://rtsp:", 14))
557 av_strlcpy(mp_filename, demuxer->stream->url + 9, sizeof(mp_filename));
558 else
559 av_strlcat(mp_filename, demuxer->stream->url, sizeof(mp_filename));
560 } else
561 av_strlcat(mp_filename, "foobar.dummy", sizeof(mp_filename));
563 priv->pb = av_alloc_put_byte(priv->buffer, BIO_BUFFER_SIZE, 0,
564 demuxer, mp_read, NULL, mp_seek);
565 priv->pb->read_seek = mp_read_seek;
566 priv->pb->is_streamed = !demuxer->stream->end_pos || (demuxer->stream->flags & MP_STREAM_SEEK) != MP_STREAM_SEEK;
568 if(av_open_input_stream(&avfc, priv->pb, mp_filename, priv->avif, &ap)<0){
569 mp_msg(MSGT_HEADER,MSGL_ERR,"LAVF_header: av_open_input_stream() failed\n");
570 return NULL;
573 priv->avfc= avfc;
575 if(av_find_stream_info(avfc) < 0){
576 mp_msg(MSGT_HEADER,MSGL_ERR,"LAVF_header: av_find_stream_info() failed\n");
577 return NULL;
580 /* Add metadata. */
581 av_metadata_conv(avfc, NULL, avfc->iformat->metadata_conv);
582 while((t = av_metadata_get(avfc->metadata, "", t, AV_METADATA_IGNORE_SUFFIX)))
583 demux_info_add(demuxer, t->key, t->value);
585 for(i=0; i < avfc->nb_chapters; i++) {
586 AVChapter *c = avfc->chapters[i];
587 uint64_t start = av_rescale_q(c->start, c->time_base, (AVRational){1,1000000000});
588 uint64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,1000000000});
589 t = av_metadata_get(c->metadata, "title", NULL, 0);
590 demuxer_add_chapter(demuxer, t ? BSTR(t->value) : BSTR(NULL), start, end);
593 for(i=0; i<avfc->nb_streams; i++)
594 handle_stream(demuxer, avfc, i);
595 priv->nb_streams_last = avfc->nb_streams;
597 if(avfc->nb_programs) {
598 int p;
599 for (p = 0; p < avfc->nb_programs; p++) {
600 AVProgram *program = avfc->programs[p];
601 t = av_metadata_get(program->metadata, "title", NULL, 0);
602 mp_msg(MSGT_HEADER,MSGL_INFO,"LAVF: Program %d %s\n", program->id, t ? t->value : "");
603 mp_msg(MSGT_IDENTIFY, MSGL_V, "PROGRAM_ID=%d\n", program->id);
607 mp_msg(MSGT_HEADER,MSGL_V,"LAVF: %d audio and %d video streams found\n",priv->audio_streams,priv->video_streams);
608 mp_msg(MSGT_HEADER,MSGL_V,"LAVF: build %d\n", LIBAVFORMAT_BUILD);
609 demuxer->audio->id = -2; // wait for higher-level code to select track
610 if(!priv->video_streams){
611 if(!priv->audio_streams){
612 mp_msg(MSGT_HEADER,MSGL_ERR,"LAVF: no audio or video headers found - broken file?\n");
613 return NULL;
615 demuxer->video->id=-2; // audio-only
616 } //else if (best_video > 0 && demuxer->video->id == -1) demuxer->video->id = best_video;
618 // disabled because unreliable per-stream bitrate values returned
619 // by libavformat trigger this heuristic incorrectly and break things
620 #if 0
621 /* libavformat sets bitrate for mpeg based on pts at start and end
622 * of file, which fails for files with pts resets. So calculate our
623 * own bitrate estimate. */
624 if (priv->avif->flags & AVFMT_TS_DISCONT) {
625 for (int i = 0; i < avfc->nb_streams; i++)
626 priv->bitrate += avfc->streams[i]->codec->bit_rate;
627 /* pts-based is more accurate if there are no resets; try to make
628 * a somewhat reasonable guess */
629 if (!avfc->duration || avfc->duration == AV_NOPTS_VALUE
630 || priv->bitrate && (avfc->bit_rate < priv->bitrate / 2
631 || avfc->bit_rate > priv->bitrate * 2))
632 priv->seek_by_bytes = true;
633 if (!priv->bitrate)
634 priv->bitrate = 1440000;
636 #endif
637 demuxer->accurate_seek = !priv->seek_by_bytes;
639 return demuxer;
642 static void check_internet_radio_hack(struct demuxer *demuxer)
644 struct lavf_priv *priv = demuxer->priv;
645 struct AVFormatContext *avfc = priv->avfc;
647 if (!matches_avinputformat_name(priv, "ogg"))
648 return;
649 if (priv->nb_streams_last == avfc->nb_streams)
650 return;
651 if (avfc->nb_streams - priv->nb_streams_last == 1
652 && priv->video_streams == 0 && priv->sub_streams == 0
653 && demuxer->a_streams[priv->audio_streams-1]->format == 0x566f // vorbis
654 && (priv->audio_streams == 2 || priv->internet_radio_hack)
655 && demuxer->a_streams[0]->format == 0x566f) {
656 // extradata match could be checked but would require parsing
657 // headers, as the comment section will vary
658 if (!priv->internet_radio_hack) {
659 mp_msg(MSGT_DEMUX, MSGL_V,
660 "[lavf] enabling internet ogg radio hack\n");
661 #if LIBAVFORMAT_VERSION_MAJOR < 53
662 mp_tmsg(MSGT_DEMUX, MSGL_WARN, "[lavf] This looks like an "
663 "internet radio ogg stream with track changes.\n"
664 "Playback will likely fail after %d track changes "
665 "due to libavformat limitations.\n"
666 "You may be able to work around that limitation by "
667 "using -demuxer ogg.\n", MAX_STREAMS);
668 #endif
670 #if LIBAVFORMAT_VERSION_MAJOR < 53
671 if (avfc->nb_streams == MAX_STREAMS) {
672 mp_tmsg(MSGT_DEMUX, MSGL_WARN, "[lavf] This is the %dth "
673 "track.\nPlayback will likely fail at the next change.\n"
674 "You may be able to work around this limitation by "
675 "using -demuxer ogg.\n", MAX_STREAMS);
677 #endif
678 priv->internet_radio_hack = true;
679 // use new per-track metadata as global metadata
680 AVMetadataTag *t = NULL;
681 AVStream *stream = avfc->streams[avfc->nb_streams - 1];
682 while ((t = av_metadata_get(stream->metadata, "", t,
683 AV_METADATA_IGNORE_SUFFIX)))
684 demux_info_add(demuxer, t->key, t->value);
685 } else {
686 if (priv->internet_radio_hack)
687 mp_tmsg(MSGT_DEMUX, MSGL_WARN, "[lavf] Internet radio ogg hack "
688 "was enabled, but stream characteristics changed.\n"
689 "This may or may not work.\n");
690 priv->internet_radio_hack = false;
694 static int demux_lavf_fill_buffer(demuxer_t *demux, demux_stream_t *dsds){
695 lavf_priv_t *priv= demux->priv;
696 AVPacket pkt;
697 demux_packet_t *dp;
698 demux_stream_t *ds;
699 int id;
700 mp_msg(MSGT_DEMUX,MSGL_DBG2,"demux_lavf_fill_buffer()\n");
702 demux->filepos=stream_tell(demux->stream);
704 if(av_read_frame(priv->avfc, &pkt) < 0)
705 return 0;
707 // handle any new streams that might have been added
708 for (id = priv->nb_streams_last; id < priv->avfc->nb_streams; id++)
709 handle_stream(demux, priv->avfc, id);
710 check_internet_radio_hack(demux);
712 priv->nb_streams_last = priv->avfc->nb_streams;
714 id= pkt.stream_index;
716 if (id == demux->audio->id || priv->internet_radio_hack) {
717 // audio
718 ds=demux->audio;
719 if(!ds->sh){
720 ds->sh=demux->a_streams[id];
721 mp_msg(MSGT_DEMUX,MSGL_V,"Auto-selected LAVF audio ID = %d\n",ds->id);
723 } else if(id==demux->video->id){
724 // video
725 ds=demux->video;
726 if(!ds->sh){
727 ds->sh=demux->v_streams[id];
728 mp_msg(MSGT_DEMUX,MSGL_V,"Auto-selected LAVF video ID = %d\n",ds->id);
730 } else if(id==demux->sub->id){
731 // subtitle
732 ds=demux->sub;
733 sub_utf8=1;
734 } else {
735 av_free_packet(&pkt);
736 return 1;
739 if(0/*pkt.destruct == av_destruct_packet*/){
740 //ok kids, dont try this at home :)
741 dp=malloc(sizeof(demux_packet_t));
742 dp->len=pkt.size;
743 dp->next=NULL;
744 dp->refcount=1;
745 dp->master=NULL;
746 dp->buffer=pkt.data;
747 pkt.destruct= NULL;
748 }else{
749 dp=new_demux_packet(pkt.size);
750 memcpy(dp->buffer, pkt.data, pkt.size);
751 av_free_packet(&pkt);
754 int64_t ts = priv->use_dts ? pkt.dts : pkt.pts;
755 if(ts != AV_NOPTS_VALUE){
756 dp->pts = ts * av_q2d(priv->avfc->streams[id]->time_base);
757 priv->last_pts= dp->pts * AV_TIME_BASE;
758 // always set duration for subtitles, even if PKT_FLAG_KEY is not set,
759 // otherwise they will stay on screen to long if e.g. ASS is demuxed from mkv
760 if((ds == demux->sub || (pkt.flags & PKT_FLAG_KEY)) &&
761 pkt.convergence_duration > 0)
762 dp->duration = pkt.convergence_duration * av_q2d(priv->avfc->streams[id]->time_base);
764 dp->pos=demux->filepos;
765 dp->flags= !!(pkt.flags&PKT_FLAG_KEY);
766 // append packet to DS stream:
767 ds_add_packet(ds,dp);
768 return 1;
771 static void demux_seek_lavf(demuxer_t *demuxer, float rel_seek_secs, float audio_delay, int flags){
772 lavf_priv_t *priv = demuxer->priv;
773 int avsflags = 0;
774 mp_msg(MSGT_DEMUX,MSGL_DBG2,"demux_seek_lavf(%p, %f, %f, %d)\n", demuxer, rel_seek_secs, audio_delay, flags);
776 if (priv->seek_by_bytes) {
777 int64_t pos = demuxer->filepos;
778 rel_seek_secs *= priv->bitrate / 8;
779 pos += rel_seek_secs;
780 av_seek_frame(priv->avfc, -1, pos, AVSEEK_FLAG_BYTE);
781 return;
784 if (flags & SEEK_ABSOLUTE) {
785 priv->last_pts = 0;
786 } else {
787 if (rel_seek_secs < 0) avsflags = AVSEEK_FLAG_BACKWARD;
789 if (flags & SEEK_FORWARD)
790 avsflags = 0;
791 else if (flags & SEEK_BACKWARD)
792 avsflags = AVSEEK_FLAG_BACKWARD;
793 if (flags & SEEK_FACTOR) {
794 if (priv->avfc->duration == 0 || priv->avfc->duration == AV_NOPTS_VALUE)
795 return;
796 priv->last_pts += rel_seek_secs * priv->avfc->duration;
797 } else {
798 priv->last_pts += rel_seek_secs * AV_TIME_BASE;
800 if (av_seek_frame(priv->avfc, -1, priv->last_pts, avsflags) < 0) {
801 avsflags ^= AVSEEK_FLAG_BACKWARD;
802 av_seek_frame(priv->avfc, -1, priv->last_pts, avsflags);
806 static int demux_lavf_control(demuxer_t *demuxer, int cmd, void *arg)
808 lavf_priv_t *priv = demuxer->priv;
810 switch (cmd) {
811 case DEMUXER_CTRL_CORRECT_PTS:
812 return DEMUXER_CTRL_OK;
813 case DEMUXER_CTRL_GET_TIME_LENGTH:
814 if (priv->seek_by_bytes) {
815 /* Our bitrate estimate may be better than would be used in
816 * otherwise similar fallback code at higher level */
817 if (demuxer->movi_end <= 0)
818 return DEMUXER_CTRL_DONTKNOW;
819 *(double *)arg = (demuxer->movi_end - demuxer->movi_start) * 8 /
820 priv->bitrate;
821 return DEMUXER_CTRL_GUESS;
823 if (priv->avfc->duration == 0 || priv->avfc->duration == AV_NOPTS_VALUE)
824 return DEMUXER_CTRL_DONTKNOW;
826 *((double *)arg) = (double)priv->avfc->duration / AV_TIME_BASE;
827 return DEMUXER_CTRL_OK;
829 case DEMUXER_CTRL_GET_PERCENT_POS:
830 if (priv->seek_by_bytes)
831 return DEMUXER_CTRL_DONTKNOW; // let it use the fallback code
832 if (priv->avfc->duration == 0 || priv->avfc->duration == AV_NOPTS_VALUE)
833 return DEMUXER_CTRL_DONTKNOW;
835 *((int *)arg) = (int)((priv->last_pts - priv->avfc->start_time)*100 / priv->avfc->duration);
836 return DEMUXER_CTRL_OK;
837 case DEMUXER_CTRL_SWITCH_AUDIO:
838 case DEMUXER_CTRL_SWITCH_VIDEO:
840 int id = *((int*)arg);
841 int newid = -2;
842 int i, curridx = -1;
843 int nstreams, *pstreams;
844 demux_stream_t *ds;
846 if(cmd == DEMUXER_CTRL_SWITCH_VIDEO)
848 ds = demuxer->video;
849 nstreams = priv->video_streams;
850 pstreams = priv->vstreams;
852 else
854 ds = demuxer->audio;
855 nstreams = priv->audio_streams;
856 pstreams = priv->astreams;
858 for(i = 0; i < nstreams; i++)
860 if(pstreams[i] == ds->id) //current stream id
862 curridx = i;
863 break;
867 if (id == -1) { // next track
868 i = (curridx + 2) % (nstreams + 1) - 1;
869 if (i >= 0)
870 newid = pstreams[i];
871 } else if (id >= 0 && id < nstreams) { // select track by id
872 i = id;
873 newid = pstreams[i];
874 } else // no sound
875 i = -1;
877 if (i == curridx) {
878 *(int *) arg = curridx < 0 ? -2 : curridx;
879 return DEMUXER_CTRL_OK;
880 } else {
881 ds_free_packs(ds);
882 if(ds->id >= 0)
883 priv->avfc->streams[ds->id]->discard = AVDISCARD_ALL;
884 ds->id = newid;
885 *(int *) arg = i < 0 ? -2 : i;
886 if(newid >= 0)
887 priv->avfc->streams[newid]->discard = AVDISCARD_NONE;
888 return DEMUXER_CTRL_OK;
891 case DEMUXER_CTRL_IDENTIFY_PROGRAM:
893 demux_program_t *prog = arg;
894 AVProgram *program;
895 int p, i;
896 int start;
898 prog->vid = prog->aid = prog->sid = -2; //no audio and no video by default
899 if(priv->avfc->nb_programs < 1)
900 return DEMUXER_CTRL_DONTKNOW;
902 if(prog->progid == -1)
904 p = 0;
905 while(p<priv->avfc->nb_programs && priv->avfc->programs[p]->id != priv->cur_program)
906 p++;
907 p = (p + 1) % priv->avfc->nb_programs;
909 else
911 for(i=0; i<priv->avfc->nb_programs; i++)
912 if(priv->avfc->programs[i]->id == prog->progid)
913 break;
914 if(i==priv->avfc->nb_programs)
915 return DEMUXER_CTRL_DONTKNOW;
916 p = i;
918 start = p;
919 redo:
920 program = priv->avfc->programs[p];
921 for(i=0; i<program->nb_stream_indexes; i++)
923 switch(priv->avfc->streams[program->stream_index[i]]->codec->codec_type)
925 case CODEC_TYPE_VIDEO:
926 if(prog->vid == -2)
927 prog->vid = program->stream_index[i];
928 break;
929 case CODEC_TYPE_AUDIO:
930 if(prog->aid == -2)
931 prog->aid = program->stream_index[i];
932 break;
933 case CODEC_TYPE_SUBTITLE:
934 if(prog->sid == -2 && priv->avfc->streams[program->stream_index[i]]->codec->codec_id == CODEC_ID_TEXT)
935 prog->sid = program->stream_index[i];
936 break;
939 if (prog->aid >= 0 && prog->aid < MAX_A_STREAMS &&
940 demuxer->a_streams[prog->aid]) {
941 sh_audio_t *sh = demuxer->a_streams[prog->aid];
942 prog->aid = sh->aid;
943 } else
944 prog->aid = -2;
945 if (prog->vid >= 0 && prog->vid < MAX_V_STREAMS &&
946 demuxer->v_streams[prog->vid]) {
947 sh_video_t *sh = demuxer->v_streams[prog->vid];
948 prog->vid = sh->vid;
949 } else
950 prog->vid = -2;
951 if(prog->progid == -1 && prog->vid == -2 && prog->aid == -2)
953 p = (p + 1) % priv->avfc->nb_programs;
954 if (p == start)
955 return DEMUXER_CTRL_DONTKNOW;
956 goto redo;
958 priv->cur_program = prog->progid = program->id;
959 return DEMUXER_CTRL_OK;
961 default:
962 return DEMUXER_CTRL_NOTIMPL;
966 static void demux_close_lavf(demuxer_t *demuxer)
968 lavf_priv_t* priv = demuxer->priv;
969 if (priv){
970 if(priv->avfc)
972 av_freep(&priv->avfc->key);
973 av_close_input_stream(priv->avfc);
975 av_freep(&priv->pb);
976 free(priv); demuxer->priv= NULL;
981 const demuxer_desc_t demuxer_desc_lavf = {
982 "libavformat demuxer",
983 "lavf",
984 "libavformat",
985 "Michael Niedermayer",
986 "supports many formats, requires libavformat",
987 DEMUXER_TYPE_LAVF,
988 0, // Check after other demuxer
989 lavf_check_file,
990 demux_lavf_fill_buffer,
991 demux_open_lavf,
992 demux_close_lavf,
993 demux_seek_lavf,
994 demux_lavf_control
997 const demuxer_desc_t demuxer_desc_lavf_preferred = {
998 "libavformat preferred demuxer",
999 "lavfpref",
1000 "libavformat",
1001 "Michael Niedermayer",
1002 "supports many formats, requires libavformat",
1003 DEMUXER_TYPE_LAVF_PREFERRED,
1005 lavf_check_preferred_file,
1006 demux_lavf_fill_buffer,
1007 demux_open_lavf,
1008 demux_close_lavf,
1009 demux_seek_lavf,
1010 demux_lavf_control