demux_lavf: try harder to make up a frame rate
[mplayer.git] / libmpdemux / demux_lavf.c
blob62cb0bad1b83f9811c5dfda6a6c52913eef9ca98
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 <libavformat/avformat.h>
29 #include <libavformat/avio.h>
30 #include <libavutil/avutil.h>
31 #include <libavutil/avstring.h>
32 #include <libavutil/mathematics.h>
33 #include <libavutil/opt.h>
35 #include "config.h"
36 #include "options.h"
37 #include "mp_msg.h"
38 #include "av_opts.h"
39 #include "bstr.h"
41 #include "stream/stream.h"
42 #include "aviprint.h"
43 #include "demuxer.h"
44 #include "stheader.h"
45 #include "m_option.h"
46 #include "sub/sub.h"
48 #include "mp_taglists.h"
50 #define INITIAL_PROBE_SIZE STREAM_BUFFER_SIZE
51 #define SMALL_MAX_PROBE_SIZE (32 * 1024)
52 #define PROBE_BUF_SIZE (2 * 1024 * 1024)
54 const m_option_t lavfdopts_conf[] = {
55 OPT_INTRANGE("probesize", lavfdopts.probesize, 0, 32, INT_MAX),
56 OPT_STRING("format", lavfdopts.format, 0),
57 OPT_INTRANGE("analyzeduration", lavfdopts.analyzeduration, 0, 0, INT_MAX),
58 OPT_STRING("cryptokey", lavfdopts.cryptokey, 0),
59 OPT_STRING("o", lavfdopts.avopt, 0),
60 {NULL, NULL, 0, 0, 0, 0, NULL}
63 #define BIO_BUFFER_SIZE 32768
65 typedef struct lavf_priv {
66 AVInputFormat *avif;
67 AVFormatContext *avfc;
68 AVIOContext *pb;
69 uint8_t buffer[BIO_BUFFER_SIZE];
70 int audio_streams;
71 int video_streams;
72 int sub_streams;
73 int64_t last_pts;
74 int astreams[MAX_A_STREAMS];
75 int vstreams[MAX_V_STREAMS];
76 int sstreams[MAX_S_STREAMS];
77 int cur_program;
78 int nb_streams_last;
79 bool internet_radio_hack;
80 bool use_dts;
81 bool seek_by_bytes;
82 int bitrate;
83 } lavf_priv_t;
85 static int mp_read(void *opaque, uint8_t *buf, int size)
87 struct demuxer *demuxer = opaque;
88 struct stream *stream = demuxer->stream;
89 int ret;
91 ret = stream_read(stream, buf, size);
93 mp_msg(MSGT_HEADER, MSGL_DBG2,
94 "%d=mp_read(%p, %p, %d), pos: %"PRId64", eof:%d\n",
95 ret, stream, buf, size, stream_tell(stream), stream->eof);
96 return ret;
99 static int64_t mp_seek(void *opaque, int64_t pos, int whence)
101 struct demuxer *demuxer = opaque;
102 struct stream *stream = demuxer->stream;
103 int64_t current_pos;
104 mp_msg(MSGT_HEADER, MSGL_DBG2, "mp_seek(%p, %"PRId64", %d)\n",
105 stream, pos, whence);
106 if (whence == SEEK_CUR)
107 pos += stream_tell(stream);
108 else if (whence == SEEK_END && stream->end_pos > 0)
109 pos += stream->end_pos;
110 else if (whence == SEEK_SET)
111 pos += stream->start_pos;
112 else if (whence == AVSEEK_SIZE && stream->end_pos > 0) {
113 off_t size;
114 if (stream_control(stream, STREAM_CTRL_GET_SIZE, &size) == STREAM_OK)
115 return size;
116 return stream->end_pos - stream->start_pos;
117 } else
118 return -1;
120 if (pos < 0)
121 return -1;
122 current_pos = stream_tell(stream);
123 if (stream_seek(stream, pos) == 0) {
124 stream_reset(stream);
125 stream_seek(stream, current_pos);
126 return -1;
129 return pos - stream->start_pos;
132 static int64_t mp_read_seek(void *opaque, int stream_idx, int64_t ts, int flags)
134 struct demuxer *demuxer = opaque;
135 struct stream *stream = demuxer->stream;
136 struct lavf_priv *priv = demuxer->priv;
138 AVStream *st = priv->avfc->streams[stream_idx];
139 double pts = (double)ts * st->time_base.num / st->time_base.den;
140 int ret = stream_control(stream, STREAM_CTRL_SEEK_TO_TIME, &pts);
141 if (ret < 0)
142 ret = AVERROR(ENOSYS);
143 return ret;
146 static void list_formats(void)
148 mp_msg(MSGT_DEMUX, MSGL_INFO, "Available lavf input formats:\n");
149 AVInputFormat *fmt = NULL;
150 while ((fmt = av_iformat_next(fmt)))
151 mp_msg(MSGT_DEMUX, MSGL_INFO, "%15s : %s\n", fmt->name, fmt->long_name);
154 static int lavf_check_file(demuxer_t *demuxer)
156 struct MPOpts *opts = demuxer->opts;
157 struct lavfdopts *lavfdopts = &opts->lavfdopts;
158 AVProbeData avpd;
159 lavf_priv_t *priv;
160 int probe_data_size = 0;
161 int read_size = INITIAL_PROBE_SIZE;
162 int score;
164 if (!demuxer->priv)
165 demuxer->priv = calloc(sizeof(lavf_priv_t), 1);
166 priv = demuxer->priv;
168 char *format = lavfdopts->format;
169 if (!format)
170 format = demuxer->stream->lavf_type;
171 if (format) {
172 if (strcmp(format, "help") == 0) {
173 list_formats();
174 return 0;
176 priv->avif = av_find_input_format(format);
177 if (!priv->avif) {
178 mp_msg(MSGT_DEMUX, MSGL_FATAL, "Unknown lavf format %s\n", format);
179 return 0;
181 mp_msg(MSGT_DEMUX, MSGL_INFO, "Forced lavf %s demuxer\n",
182 priv->avif->long_name);
183 return DEMUXER_TYPE_LAVF;
186 avpd.buf = av_mallocz(FFMAX(BIO_BUFFER_SIZE, PROBE_BUF_SIZE) +
187 FF_INPUT_BUFFER_PADDING_SIZE);
188 do {
189 read_size = stream_read(demuxer->stream, avpd.buf + probe_data_size,
190 read_size);
191 if (read_size < 0) {
192 av_free(avpd.buf);
193 return 0;
195 probe_data_size += read_size;
196 avpd.filename = demuxer->stream->url;
197 if (!avpd.filename) {
198 mp_msg(MSGT_DEMUX, MSGL_WARN, "Stream url is not set!\n");
199 avpd.filename = "";
201 if (!strncmp(avpd.filename, "ffmpeg://", 9))
202 avpd.filename += 9;
203 avpd.buf_size = probe_data_size;
205 score = 0;
206 priv->avif = av_probe_input_format2(&avpd, probe_data_size > 0, &score);
207 read_size = FFMIN(2 * read_size, PROBE_BUF_SIZE - probe_data_size);
208 } while ((demuxer->desc->type != DEMUXER_TYPE_LAVF_PREFERRED ||
209 probe_data_size < SMALL_MAX_PROBE_SIZE) &&
210 score <= AVPROBE_SCORE_MAX / 4 &&
211 read_size > 0 && probe_data_size < PROBE_BUF_SIZE);
212 av_free(avpd.buf);
214 if (!priv->avif || score <= AVPROBE_SCORE_MAX / 4) {
215 mp_msg(MSGT_HEADER, MSGL_V,
216 "LAVF_check: no clue about this gibberish!\n");
217 return 0;
218 } else
219 mp_msg(MSGT_HEADER, MSGL_V, "LAVF_check: %s\n", priv->avif->long_name);
221 demuxer->filetype = priv->avif->long_name;
222 if (!demuxer->filetype)
223 demuxer->filetype = priv->avif->name;
225 return DEMUXER_TYPE_LAVF;
228 static bool matches_avinputformat_name(struct lavf_priv *priv,
229 const char *name)
231 const char *avifname = priv->avif->name;
232 while (1) {
233 const char *next = strchr(avifname, ',');
234 if (!next)
235 return !strcmp(avifname, name);
236 int len = next - avifname;
237 if (len == strlen(name) && !memcmp(avifname, name, len))
238 return true;
239 avifname = next + 1;
243 /* formats for which an internal demuxer is preferred */
244 static const char * const preferred_internal[] = {
245 /* lavf Matroska demuxer doesn't support ordered chapters and fails
246 * for more files */
247 "matroska",
248 /* lavf gives neither pts nor dts for some video frames in .rm */
249 "rm",
250 NULL
253 static int lavf_check_preferred_file(demuxer_t *demuxer)
255 if (lavf_check_file(demuxer)) {
256 const char * const *p;
257 lavf_priv_t *priv = demuxer->priv;
258 for (p = preferred_internal; *p; p++)
259 if (matches_avinputformat_name(priv, *p))
260 return 0;
261 return DEMUXER_TYPE_LAVF_PREFERRED;
263 return 0;
266 static uint8_t char2int(char c)
268 if (c >= '0' && c <= '9') return c - '0';
269 if (c >= 'a' && c <= 'f') return c - 'a' + 10;
270 if (c >= 'A' && c <= 'F') return c - 'A' + 10;
271 return 0;
274 static void parse_cryptokey(AVFormatContext *avfc, const char *str)
276 int len = strlen(str) / 2;
277 uint8_t *key = av_mallocz(len);
278 int i;
279 avfc->keylen = len;
280 avfc->key = key;
281 for (i = 0; i < len; i++, str += 2)
282 *key++ = (char2int(str[0]) << 4) | char2int(str[1]);
285 static void handle_stream(demuxer_t *demuxer, AVFormatContext *avfc, int i)
287 lavf_priv_t *priv = demuxer->priv;
288 AVStream *st = avfc->streams[i];
289 AVCodecContext *codec = st->codec;
290 char *stream_type = NULL;
291 int stream_id;
292 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL, 0);
293 AVDictionaryEntry *title = av_dict_get(st->metadata, "title", NULL, 0);
294 // Don't use native MPEG codec tag values with our generic tag tables.
295 // May contain for example value 3 for MP3, which we'd map to PCM audio.
296 if (matches_avinputformat_name(priv, "mpeg") ||
297 matches_avinputformat_name(priv, "mpegts"))
298 codec->codec_tag = 0;
299 int override_tag = mp_taglist_override(codec->codec_id);
300 // For some formats (like PCM) always trust CODEC_ID_* more than codec_tag
301 if (override_tag)
302 codec->codec_tag = override_tag;
304 switch (codec->codec_type) {
305 case AVMEDIA_TYPE_AUDIO: {
306 WAVEFORMATEX *wf;
307 sh_audio_t *sh_audio;
308 sh_audio = new_sh_audio_aid(demuxer, i, priv->audio_streams);
309 if (!sh_audio)
310 break;
311 stream_type = "audio";
312 priv->astreams[priv->audio_streams] = i;
313 wf = calloc(sizeof(*wf) + codec->extradata_size, 1);
314 // mp4a tag is used for all mp4 files no matter what they actually contain
315 if (codec->codec_tag == MKTAG('m', 'p', '4', 'a'))
316 codec->codec_tag = 0;
317 if (!codec->codec_tag)
318 codec->codec_tag = mp_taglist_audio(codec->codec_id);
319 wf->wFormatTag = codec->codec_tag;
320 wf->nChannels = codec->channels;
321 wf->nSamplesPerSec = codec->sample_rate;
322 wf->nAvgBytesPerSec = codec->bit_rate / 8;
323 wf->nBlockAlign = codec->block_align ? codec->block_align : 1;
324 wf->wBitsPerSample = codec->bits_per_coded_sample;
325 wf->cbSize = codec->extradata_size;
326 if (codec->extradata_size)
327 memcpy(wf + 1, codec->extradata, codec->extradata_size);
328 sh_audio->wf = wf;
329 sh_audio->audio.dwSampleSize = codec->block_align;
330 if (codec->frame_size && codec->sample_rate) {
331 sh_audio->audio.dwScale = codec->frame_size;
332 sh_audio->audio.dwRate = codec->sample_rate;
333 } else {
334 sh_audio->audio.dwScale = codec->block_align ? codec->block_align * 8 : 8;
335 sh_audio->audio.dwRate = codec->bit_rate;
337 int g = av_gcd(sh_audio->audio.dwScale, sh_audio->audio.dwRate);
338 sh_audio->audio.dwScale /= g;
339 sh_audio->audio.dwRate /= g;
340 // 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);
341 sh_audio->ds = demuxer->audio;
342 sh_audio->format = codec->codec_tag;
343 sh_audio->channels = codec->channels;
344 sh_audio->samplerate = codec->sample_rate;
345 sh_audio->i_bps = codec->bit_rate / 8;
346 switch (codec->codec_id) {
347 case CODEC_ID_PCM_S8:
348 case CODEC_ID_PCM_U8:
349 sh_audio->samplesize = 1;
350 break;
351 case CODEC_ID_PCM_S16LE:
352 case CODEC_ID_PCM_S16BE:
353 case CODEC_ID_PCM_U16LE:
354 case CODEC_ID_PCM_U16BE:
355 sh_audio->samplesize = 2;
356 break;
357 case CODEC_ID_PCM_ALAW:
358 sh_audio->format = 0x6;
359 break;
360 case CODEC_ID_PCM_MULAW:
361 sh_audio->format = 0x7;
362 break;
364 if (title && title->value) {
365 sh_audio->title = talloc_strdup(sh_audio, title->value);
366 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AID_%d_NAME=%s\n",
367 priv->audio_streams, title->value);
369 if (lang && lang->value) {
370 sh_audio->lang = talloc_strdup(sh_audio, lang->value);
371 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AID_%d_LANG=%s\n",
372 priv->audio_streams, sh_audio->lang);
374 if (st->disposition & AV_DISPOSITION_DEFAULT)
375 sh_audio->default_track = 1;
376 if (mp_msg_test(MSGT_HEADER, MSGL_V))
377 print_wave_header(sh_audio->wf, MSGL_V);
378 st->discard = AVDISCARD_ALL;
379 stream_id = priv->audio_streams++;
380 break;
382 case AVMEDIA_TYPE_VIDEO: {
383 sh_video_t *sh_video;
384 BITMAPINFOHEADER *bih;
385 sh_video = new_sh_video_vid(demuxer, i, priv->video_streams);
386 if (!sh_video)
387 break;
388 stream_type = "video";
389 priv->vstreams[priv->video_streams] = i;
390 bih = calloc(sizeof(*bih) + codec->extradata_size, 1);
392 if (codec->codec_id == CODEC_ID_RAWVIDEO) {
393 switch (codec->pix_fmt) {
394 case PIX_FMT_RGB24:
395 codec->codec_tag = MKTAG(24, 'B', 'G', 'R');
396 case PIX_FMT_BGR24:
397 codec->codec_tag = MKTAG(24, 'R', 'G', 'B');
399 if (!codec->codec_tag)
400 codec->codec_tag = avcodec_pix_fmt_to_codec_tag(codec->pix_fmt);
402 if (!codec->codec_tag)
403 codec->codec_tag = mp_taglist_video(codec->codec_id);
404 bih->biSize = sizeof(*bih) + codec->extradata_size;
405 bih->biWidth = codec->width;
406 bih->biHeight = codec->height;
407 bih->biBitCount = codec->bits_per_coded_sample;
408 bih->biSizeImage = bih->biWidth * bih->biHeight * bih->biBitCount / 8;
409 bih->biCompression = codec->codec_tag;
410 sh_video->bih = bih;
411 sh_video->disp_w = codec->width;
412 sh_video->disp_h = codec->height;
413 if (st->time_base.den) { /* if container has time_base, use that */
414 sh_video->video.dwRate = st->time_base.den;
415 sh_video->video.dwScale = st->time_base.num;
416 } else {
417 sh_video->video.dwRate = codec->time_base.den;
418 sh_video->video.dwScale = codec->time_base.num;
420 /* Try to make up some frame rate value, even if it's not reliable.
421 * FPS information is needed to support subtitle formats which base
422 * timing on frame numbers.
423 * Libavformat seems to report no "reliable" FPS value for AVI files,
424 * while they are typically constant enough FPS that the value this
425 * heuristic makes up works with subtitles in practice.
427 double fps;
428 if (st->r_frame_rate.num)
429 fps = av_q2d(st->r_frame_rate);
430 else
431 fps = 1.0 / FFMAX(av_q2d(st->time_base),
432 av_q2d(st->codec->time_base) *
433 st->codec->ticks_per_frame);
434 sh_video->fps = fps;
435 sh_video->frametime = 1 / fps;
436 sh_video->format = bih->biCompression;
437 if (st->sample_aspect_ratio.num)
438 sh_video->aspect = codec->width * st->sample_aspect_ratio.num
439 / (float)(codec->height * st->sample_aspect_ratio.den);
440 else
441 sh_video->aspect = codec->width * codec->sample_aspect_ratio.num
442 / (float)(codec->height * codec->sample_aspect_ratio.den);
443 sh_video->i_bps = codec->bit_rate / 8;
444 if (title && title->value) {
445 sh_video->title = talloc_strdup(sh_video, title->value);
446 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VID_%d_NAME=%s\n",
447 priv->video_streams, title->value);
449 mp_msg(MSGT_DEMUX, MSGL_DBG2, "aspect= %d*%d/(%d*%d)\n",
450 codec->width, codec->sample_aspect_ratio.num,
451 codec->height, codec->sample_aspect_ratio.den);
453 sh_video->ds = demuxer->video;
454 if (codec->extradata_size)
455 memcpy(sh_video->bih + 1, codec->extradata, codec->extradata_size);
456 if ( mp_msg_test(MSGT_HEADER, MSGL_V))
457 print_video_header(sh_video->bih, MSGL_V);
458 if (demuxer->video->id != priv->video_streams
459 && demuxer->video->id != -1)
460 st->discard = AVDISCARD_ALL;
461 else {
462 demuxer->video->id = i;
463 demuxer->video->sh = demuxer->v_streams[i];
465 stream_id = priv->video_streams++;
466 break;
468 case AVMEDIA_TYPE_SUBTITLE: {
469 sh_sub_t *sh_sub;
470 char type;
471 /* only support text subtitles for now */
472 if (codec->codec_id == CODEC_ID_TEXT)
473 type = 't';
474 else if (codec->codec_id == CODEC_ID_MOV_TEXT)
475 type = 'm';
476 else if (codec->codec_id == CODEC_ID_SSA)
477 type = 'a';
478 else if (codec->codec_id == CODEC_ID_DVD_SUBTITLE)
479 type = 'v';
480 else if (codec->codec_id == CODEC_ID_XSUB)
481 type = 'x';
482 else if (codec->codec_id == CODEC_ID_DVB_SUBTITLE)
483 type = 'b';
484 else if (codec->codec_id == CODEC_ID_DVB_TELETEXT)
485 type = 'd';
486 else if (codec->codec_id == CODEC_ID_HDMV_PGS_SUBTITLE)
487 type = 'p';
488 else
489 break;
490 sh_sub = new_sh_sub_sid(demuxer, i, priv->sub_streams);
491 if (!sh_sub)
492 break;
493 stream_type = "subtitle";
494 priv->sstreams[priv->sub_streams] = i;
495 sh_sub->type = type;
496 if (codec->extradata_size) {
497 sh_sub->extradata = malloc(codec->extradata_size);
498 memcpy(sh_sub->extradata, codec->extradata, codec->extradata_size);
499 sh_sub->extradata_len = codec->extradata_size;
501 if (title && title->value) {
502 sh_sub->title = talloc_strdup(sh_sub, title->value);
503 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SID_%d_NAME=%s\n",
504 priv->sub_streams, title->value);
506 if (lang && lang->value) {
507 sh_sub->lang = talloc_strdup(sh_sub, lang->value);
508 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SID_%d_LANG=%s\n",
509 priv->sub_streams, sh_sub->lang);
511 if (st->disposition & AV_DISPOSITION_DEFAULT)
512 sh_sub->default_track = 1;
513 stream_id = priv->sub_streams++;
514 break;
516 case AVMEDIA_TYPE_ATTACHMENT: {
517 AVDictionaryEntry *ftag = av_dict_get(st->metadata, "filename",
518 NULL, 0);
519 char *filename = ftag ? ftag->value : NULL;
520 if (st->codec->codec_id == CODEC_ID_TTF)
521 demuxer_add_attachment(demuxer, bstr(filename),
522 bstr("application/x-truetype-font"),
523 (struct bstr){codec->extradata,
524 codec->extradata_size});
525 break;
527 default:
528 st->discard = AVDISCARD_ALL;
530 if (stream_type) {
531 AVCodec *avc = avcodec_find_decoder(codec->codec_id);
532 const char *codec_name = avc ? avc->name : "unknown";
533 if (!avc && *stream_type == 's' && demuxer->s_streams[i])
534 codec_name = sh_sub_type2str((demuxer->s_streams[i])->type);
535 mp_msg(MSGT_DEMUX, MSGL_INFO, "[lavf] stream %d: %s (%s), -%cid %d",
536 i, stream_type, codec_name, *stream_type, stream_id);
537 if (lang && lang->value && *stream_type != 'v')
538 mp_msg(MSGT_DEMUX, MSGL_INFO, ", -%clang %s",
539 *stream_type, lang->value);
540 if (title && title->value)
541 mp_msg(MSGT_DEMUX, MSGL_INFO, ", %s", title->value);
542 mp_msg(MSGT_DEMUX, MSGL_INFO, "\n");
546 static demuxer_t *demux_open_lavf(demuxer_t *demuxer)
548 struct MPOpts *opts = demuxer->opts;
549 struct lavfdopts *lavfdopts = &opts->lavfdopts;
550 AVFormatContext *avfc;
551 AVDictionaryEntry *t = NULL;
552 lavf_priv_t *priv = demuxer->priv;
553 int i;
554 char mp_filename[256] = "mp:";
556 stream_seek(demuxer->stream, 0);
558 avfc = avformat_alloc_context();
560 if (lavfdopts->cryptokey)
561 parse_cryptokey(avfc, lavfdopts->cryptokey);
562 if (matches_avinputformat_name(priv, "avi")) {
563 /* for avi libavformat returns the avi timestamps in .dts,
564 * some made-up stuff that's not really pts in .pts */
565 priv->use_dts = true;
566 demuxer->timestamp_type = TIMESTAMP_TYPE_SORT;
567 } else {
568 if (opts->user_correct_pts != 0)
569 avfc->flags |= AVFMT_FLAG_GENPTS;
571 if (index_mode == 0)
572 avfc->flags |= AVFMT_FLAG_IGNIDX;
574 if (lavfdopts->probesize) {
575 if (av_opt_set_int(avfc, "probesize", lavfdopts->probesize, 0) < 0)
576 mp_msg(MSGT_HEADER, MSGL_ERR,
577 "demux_lavf, couldn't set option probesize to %u\n",
578 lavfdopts->probesize);
580 if (lavfdopts->analyzeduration) {
581 if (av_opt_set_int(avfc, "analyzeduration",
582 lavfdopts->analyzeduration * AV_TIME_BASE, 0) < 0)
583 mp_msg(MSGT_HEADER, MSGL_ERR, "demux_lavf, couldn't set option "
584 "analyzeduration to %u\n", lavfdopts->analyzeduration);
587 if (lavfdopts->avopt) {
588 if (parse_avopts(avfc, lavfdopts->avopt) < 0) {
589 mp_msg(MSGT_HEADER, MSGL_ERR,
590 "Your options /%s/ look like gibberish to me pal\n",
591 lavfdopts->avopt);
592 return NULL;
596 if (demuxer->stream->url) {
597 if (!strncmp(demuxer->stream->url, "ffmpeg://rtsp:", 14))
598 av_strlcpy(mp_filename, demuxer->stream->url + 9,
599 sizeof(mp_filename));
600 else
601 av_strlcat(mp_filename, demuxer->stream->url, sizeof(mp_filename));
602 } else
603 av_strlcat(mp_filename, "foobar.dummy", sizeof(mp_filename));
605 if (!(priv->avif->flags & AVFMT_NOFILE)) {
606 priv->pb = avio_alloc_context(priv->buffer, BIO_BUFFER_SIZE, 0,
607 demuxer, mp_read, NULL, mp_seek);
608 priv->pb->read_seek = mp_read_seek;
609 priv->pb->seekable = demuxer->stream->end_pos
610 && (demuxer->stream->flags & MP_STREAM_SEEK) == MP_STREAM_SEEK
611 ? AVIO_SEEKABLE_NORMAL : 0;
612 avfc->pb = priv->pb;
615 if (avformat_open_input(&avfc, mp_filename, priv->avif, NULL) < 0) {
616 mp_msg(MSGT_HEADER, MSGL_ERR,
617 "LAVF_header: avformat_open_input() failed\n");
618 return NULL;
621 priv->avfc = avfc;
623 if (avformat_find_stream_info(avfc, NULL) < 0) {
624 mp_msg(MSGT_HEADER, MSGL_ERR,
625 "LAVF_header: av_find_stream_info() failed\n");
626 return NULL;
629 /* Add metadata. */
630 while ((t = av_dict_get(avfc->metadata, "", t,
631 AV_DICT_IGNORE_SUFFIX)))
632 demux_info_add(demuxer, t->key, t->value);
634 for (i = 0; i < avfc->nb_chapters; i++) {
635 AVChapter *c = avfc->chapters[i];
636 uint64_t start = av_rescale_q(c->start, c->time_base,
637 (AVRational){1, 1000000000});
638 uint64_t end = av_rescale_q(c->end, c->time_base,
639 (AVRational){1, 1000000000});
640 t = av_dict_get(c->metadata, "title", NULL, 0);
641 demuxer_add_chapter(demuxer, t ? bstr(t->value) : bstr(NULL),
642 start, end);
645 for (i = 0; i < avfc->nb_streams; i++)
646 handle_stream(demuxer, avfc, i);
647 priv->nb_streams_last = avfc->nb_streams;
649 if (avfc->nb_programs) {
650 int p;
651 for (p = 0; p < avfc->nb_programs; p++) {
652 AVProgram *program = avfc->programs[p];
653 t = av_dict_get(program->metadata, "title", NULL, 0);
654 mp_msg(MSGT_HEADER, MSGL_INFO, "LAVF: Program %d %s\n",
655 program->id, t ? t->value : "");
656 mp_msg(MSGT_IDENTIFY, MSGL_V, "PROGRAM_ID=%d\n", program->id);
660 mp_msg(MSGT_HEADER, MSGL_V, "LAVF: %d audio and %d video streams found\n",
661 priv->audio_streams, priv->video_streams);
662 mp_msg(MSGT_HEADER, MSGL_V, "LAVF: build %d\n", LIBAVFORMAT_BUILD);
663 demuxer->audio->id = -2; // wait for higher-level code to select track
664 if (!priv->video_streams) {
665 if (!priv->audio_streams) {
666 mp_msg(MSGT_HEADER, MSGL_ERR,
667 "LAVF: no audio or video headers found - broken file?\n");
668 return NULL;
670 demuxer->video->id = -2; // audio-only
673 // disabled because unreliable per-stream bitrate values returned
674 // by libavformat trigger this heuristic incorrectly and break things
675 #if 0
676 /* libavformat sets bitrate for mpeg based on pts at start and end
677 * of file, which fails for files with pts resets. So calculate our
678 * own bitrate estimate. */
679 if (priv->avif->flags & AVFMT_TS_DISCONT) {
680 for (int i = 0; i < avfc->nb_streams; i++)
681 priv->bitrate += avfc->streams[i]->codec->bit_rate;
682 /* pts-based is more accurate if there are no resets; try to make
683 * a somewhat reasonable guess */
684 if (!avfc->duration || avfc->duration == AV_NOPTS_VALUE
685 || priv->bitrate && (avfc->bit_rate < priv->bitrate / 2
686 || avfc->bit_rate > priv->bitrate * 2))
687 priv->seek_by_bytes = true;
688 if (!priv->bitrate)
689 priv->bitrate = 1440000;
691 #endif
692 demuxer->accurate_seek = !priv->seek_by_bytes;
694 return demuxer;
697 static void check_internet_radio_hack(struct demuxer *demuxer)
699 struct lavf_priv *priv = demuxer->priv;
700 struct AVFormatContext *avfc = priv->avfc;
702 if (!matches_avinputformat_name(priv, "ogg"))
703 return;
704 if (priv->nb_streams_last == avfc->nb_streams)
705 return;
706 if (avfc->nb_streams - priv->nb_streams_last == 1
707 && priv->video_streams == 0 && priv->sub_streams == 0
708 && demuxer->a_streams[priv->audio_streams - 1]->format == 0x566f // vorbis
709 && (priv->audio_streams == 2 || priv->internet_radio_hack)
710 && demuxer->a_streams[0]->format == 0x566f) {
711 // extradata match could be checked but would require parsing
712 // headers, as the comment section will vary
713 if (!priv->internet_radio_hack) {
714 mp_msg(MSGT_DEMUX, MSGL_V,
715 "[lavf] enabling internet ogg radio hack\n");
717 priv->internet_radio_hack = true;
718 // use new per-track metadata as global metadata
719 AVDictionaryEntry *t = NULL;
720 AVStream *stream = avfc->streams[avfc->nb_streams - 1];
721 while ((t = av_dict_get(stream->metadata, "", t,
722 AV_DICT_IGNORE_SUFFIX)))
723 demux_info_add(demuxer, t->key, t->value);
724 } else {
725 if (priv->internet_radio_hack)
726 mp_tmsg(MSGT_DEMUX, MSGL_WARN, "[lavf] Internet radio ogg hack "
727 "was enabled, but stream characteristics changed.\n"
728 "This may or may not work.\n");
729 priv->internet_radio_hack = false;
733 static int destroy_avpacket(void *pkt)
735 av_free_packet(pkt);
736 return 0;
739 static int demux_lavf_fill_buffer(demuxer_t *demux, demux_stream_t *dsds)
741 lavf_priv_t *priv = demux->priv;
742 demux_packet_t *dp;
743 demux_stream_t *ds;
744 int id;
745 mp_msg(MSGT_DEMUX, MSGL_DBG2, "demux_lavf_fill_buffer()\n");
747 demux->filepos = stream_tell(demux->stream);
749 AVPacket *pkt = talloc(NULL, AVPacket);
750 if (av_read_frame(priv->avfc, pkt) < 0) {
751 talloc_free(pkt);
752 return 0;
754 talloc_set_destructor(pkt, destroy_avpacket);
756 // handle any new streams that might have been added
757 for (id = priv->nb_streams_last; id < priv->avfc->nb_streams; id++)
758 handle_stream(demux, priv->avfc, id);
759 check_internet_radio_hack(demux);
761 priv->nb_streams_last = priv->avfc->nb_streams;
763 id = pkt->stream_index;
765 if (id == demux->audio->id || priv->internet_radio_hack) {
766 // audio
767 ds = demux->audio;
768 if (!ds->sh) {
769 ds->sh = demux->a_streams[id];
770 mp_msg(MSGT_DEMUX, MSGL_V, "Auto-selected LAVF audio ID = %d\n",
771 ds->id);
773 } else if (id == demux->video->id) {
774 // video
775 ds = demux->video;
776 if (!ds->sh) {
777 ds->sh = demux->v_streams[id];
778 mp_msg(MSGT_DEMUX, MSGL_V, "Auto-selected LAVF video ID = %d\n",
779 ds->id);
781 } else if (id == demux->sub->id) {
782 // subtitle
783 ds = demux->sub;
784 sub_utf8 = 1;
785 } else {
786 talloc_free(pkt);
787 return 1;
790 // If the packet has pointers to temporary fields that could be
791 // overwritten/freed by next av_read_frame(), copy them to persistent
792 // allocations so we can safely queue the packet for any length of time.
793 if (av_dup_packet(pkt) < 0)
794 abort();
795 dp = new_demux_packet_fromdata(pkt->data, pkt->size);
796 dp->avpacket = pkt;
798 int64_t ts = priv->use_dts ? pkt->dts : pkt->pts;
799 if (ts != AV_NOPTS_VALUE) {
800 dp->pts = ts * av_q2d(priv->avfc->streams[id]->time_base);
801 priv->last_pts = dp->pts * AV_TIME_BASE;
802 // always set duration for subtitles, even if AV_PKT_FLAG_KEY isn't set,
803 // otherwise they will stay on screen to long if e.g. ASS is demuxed
804 // from mkv
805 if ((ds == demux->sub || (pkt->flags & AV_PKT_FLAG_KEY)) &&
806 pkt->convergence_duration > 0)
807 dp->duration = pkt->convergence_duration *
808 av_q2d(priv->avfc->streams[id]->time_base);
810 dp->pos = demux->filepos;
811 dp->flags = !!(pkt->flags & AV_PKT_FLAG_KEY);
812 // append packet to DS stream:
813 ds_add_packet(ds, dp);
814 return 1;
817 static void demux_seek_lavf(demuxer_t *demuxer, float rel_seek_secs,
818 float audio_delay, int flags)
820 lavf_priv_t *priv = demuxer->priv;
821 int avsflags = 0;
822 mp_msg(MSGT_DEMUX, MSGL_DBG2, "demux_seek_lavf(%p, %f, %f, %d)\n",
823 demuxer, rel_seek_secs, audio_delay, flags);
825 if (priv->seek_by_bytes) {
826 int64_t pos = demuxer->filepos;
827 rel_seek_secs *= priv->bitrate / 8;
828 pos += rel_seek_secs;
829 av_seek_frame(priv->avfc, -1, pos, AVSEEK_FLAG_BYTE);
830 return;
833 if (flags & SEEK_ABSOLUTE)
834 priv->last_pts = 0;
835 else if (rel_seek_secs < 0)
836 avsflags = AVSEEK_FLAG_BACKWARD;
837 if (flags & SEEK_FORWARD)
838 avsflags = 0;
839 else if (flags & SEEK_BACKWARD)
840 avsflags = AVSEEK_FLAG_BACKWARD;
841 if (flags & SEEK_FACTOR) {
842 if (priv->avfc->duration == 0 || priv->avfc->duration == AV_NOPTS_VALUE)
843 return;
844 priv->last_pts += rel_seek_secs * priv->avfc->duration;
845 } else
846 priv->last_pts += rel_seek_secs * AV_TIME_BASE;
847 if (av_seek_frame(priv->avfc, -1, priv->last_pts, avsflags) < 0) {
848 avsflags ^= AVSEEK_FLAG_BACKWARD;
849 av_seek_frame(priv->avfc, -1, priv->last_pts, avsflags);
853 static int demux_lavf_control(demuxer_t *demuxer, int cmd, void *arg)
855 lavf_priv_t *priv = demuxer->priv;
857 switch (cmd) {
858 case DEMUXER_CTRL_CORRECT_PTS:
859 return DEMUXER_CTRL_OK;
860 case DEMUXER_CTRL_GET_TIME_LENGTH:
861 if (priv->seek_by_bytes) {
862 /* Our bitrate estimate may be better than would be used in
863 * otherwise similar fallback code at higher level */
864 if (demuxer->movi_end <= 0)
865 return DEMUXER_CTRL_DONTKNOW;
866 *(double *)arg = (demuxer->movi_end - demuxer->movi_start) * 8 /
867 priv->bitrate;
868 return DEMUXER_CTRL_GUESS;
870 if (priv->avfc->duration == 0 || priv->avfc->duration == AV_NOPTS_VALUE)
871 return DEMUXER_CTRL_DONTKNOW;
873 *((double *)arg) = (double)priv->avfc->duration / AV_TIME_BASE;
874 return DEMUXER_CTRL_OK;
876 case DEMUXER_CTRL_GET_PERCENT_POS:
877 if (priv->seek_by_bytes)
878 return DEMUXER_CTRL_DONTKNOW; // let it use the fallback code
879 if (priv->avfc->duration == 0 || priv->avfc->duration == AV_NOPTS_VALUE)
880 return DEMUXER_CTRL_DONTKNOW;
882 *((int *)arg) = (int)((priv->last_pts - priv->avfc->start_time) * 100 /
883 priv->avfc->duration);
884 return DEMUXER_CTRL_OK;
885 case DEMUXER_CTRL_SWITCH_AUDIO:
886 case DEMUXER_CTRL_SWITCH_VIDEO:
888 int id = *((int *)arg);
889 int newid = -2;
890 int i, curridx = -1;
891 int nstreams, *pstreams;
892 demux_stream_t *ds;
894 if (cmd == DEMUXER_CTRL_SWITCH_VIDEO) {
895 ds = demuxer->video;
896 nstreams = priv->video_streams;
897 pstreams = priv->vstreams;
898 } else {
899 ds = demuxer->audio;
900 nstreams = priv->audio_streams;
901 pstreams = priv->astreams;
903 for (i = 0; i < nstreams; i++) {
904 if (pstreams[i] == ds->id) { //current stream id
905 curridx = i;
906 break;
910 if (id == -1) { // next track
911 i = (curridx + 2) % (nstreams + 1) - 1;
912 if (i >= 0)
913 newid = pstreams[i];
914 } else if (id >= 0 && id < nstreams) { // select track by id
915 i = id;
916 newid = pstreams[i];
917 } else // no sound
918 i = -1;
920 if (i == curridx) {
921 *(int *) arg = curridx < 0 ? -2 : curridx;
922 return DEMUXER_CTRL_OK;
923 } else {
924 ds_free_packs(ds);
925 if (ds->id >= 0)
926 priv->avfc->streams[ds->id]->discard = AVDISCARD_ALL;
927 ds->id = newid;
928 *(int *) arg = i < 0 ? -2 : i;
929 if (newid >= 0)
930 priv->avfc->streams[newid]->discard = AVDISCARD_NONE;
931 return DEMUXER_CTRL_OK;
934 case DEMUXER_CTRL_IDENTIFY_PROGRAM:
936 demux_program_t *prog = arg;
937 AVProgram *program;
938 int p, i;
939 int start;
941 prog->vid = prog->aid = prog->sid = -2;
942 if (priv->avfc->nb_programs < 1)
943 return DEMUXER_CTRL_DONTKNOW;
945 if (prog->progid == -1) {
946 p = 0;
947 while (p < priv->avfc->nb_programs && priv->avfc->programs[p]->id != priv->cur_program)
948 p++;
949 p = (p + 1) % priv->avfc->nb_programs;
950 } else {
951 for (i = 0; i < priv->avfc->nb_programs; i++)
952 if (priv->avfc->programs[i]->id == prog->progid)
953 break;
954 if (i == priv->avfc->nb_programs)
955 return DEMUXER_CTRL_DONTKNOW;
956 p = i;
958 start = p;
959 redo:
960 program = priv->avfc->programs[p];
961 for (i = 0; i < program->nb_stream_indexes; i++) {
962 switch (priv->avfc->streams[program->stream_index[i]]->codec->codec_type) {
963 case AVMEDIA_TYPE_VIDEO:
964 if (prog->vid == -2)
965 prog->vid = program->stream_index[i];
966 break;
967 case AVMEDIA_TYPE_AUDIO:
968 if (prog->aid == -2)
969 prog->aid = program->stream_index[i];
970 break;
971 case AVMEDIA_TYPE_SUBTITLE:
972 if (prog->sid == -2 && priv->avfc->streams[program->stream_index[i]]->codec->codec_id == CODEC_ID_TEXT)
973 prog->sid = program->stream_index[i];
974 break;
977 if (prog->aid >= 0 && prog->aid < MAX_A_STREAMS &&
978 demuxer->a_streams[prog->aid]) {
979 sh_audio_t *sh = demuxer->a_streams[prog->aid];
980 prog->aid = sh->aid;
981 } else
982 prog->aid = -2;
983 if (prog->vid >= 0 && prog->vid < MAX_V_STREAMS &&
984 demuxer->v_streams[prog->vid]) {
985 sh_video_t *sh = demuxer->v_streams[prog->vid];
986 prog->vid = sh->vid;
987 } else
988 prog->vid = -2;
989 if (prog->progid == -1 && prog->vid == -2 && prog->aid == -2) {
990 p = (p + 1) % priv->avfc->nb_programs;
991 if (p == start)
992 return DEMUXER_CTRL_DONTKNOW;
993 goto redo;
995 priv->cur_program = prog->progid = program->id;
996 return DEMUXER_CTRL_OK;
998 default:
999 return DEMUXER_CTRL_NOTIMPL;
1003 static void demux_close_lavf(demuxer_t *demuxer)
1005 lavf_priv_t *priv = demuxer->priv;
1006 if (priv) {
1007 if (priv->avfc) {
1008 av_freep(&priv->avfc->key);
1009 avformat_close_input(&priv->avfc);
1011 av_freep(&priv->pb);
1012 free(priv);
1013 demuxer->priv = NULL;
1018 const demuxer_desc_t demuxer_desc_lavf = {
1019 "libavformat demuxer",
1020 "lavf",
1021 "libavformat",
1022 "Michael Niedermayer",
1023 "supports many formats, requires libavformat",
1024 DEMUXER_TYPE_LAVF,
1025 0, // Check after other demuxer
1026 lavf_check_file,
1027 demux_lavf_fill_buffer,
1028 demux_open_lavf,
1029 demux_close_lavf,
1030 demux_seek_lavf,
1031 demux_lavf_control
1034 const demuxer_desc_t demuxer_desc_lavf_preferred = {
1035 "libavformat preferred demuxer",
1036 "lavfpref",
1037 "libavformat",
1038 "Michael Niedermayer",
1039 "supports many formats, requires libavformat",
1040 DEMUXER_TYPE_LAVF_PREFERRED,
1042 lavf_check_preferred_file,
1043 demux_lavf_fill_buffer,
1044 demux_open_lavf,
1045 demux_close_lavf,
1046 demux_seek_lavf,
1047 demux_lavf_control