docs: document --quvi-format
[mplayer.git] / libmpdemux / demux_lavf.c
blob1a30008b8f859ff9ab1ac83f7e36a67a14cbe05e
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"
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 AVIOContext *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)
86 struct demuxer *demuxer = opaque;
87 struct stream *stream = demuxer->stream;
88 int ret;
90 ret = stream_read(stream, buf, size);
92 mp_msg(MSGT_HEADER, MSGL_DBG2,
93 "%d=mp_read(%p, %p, %d), pos: %"PRId64", eof:%d\n",
94 ret, stream, buf, size, stream_tell(stream), stream->eof);
95 return ret;
98 static int64_t mp_seek(void *opaque, int64_t pos, int whence)
100 struct demuxer *demuxer = opaque;
101 struct stream *stream = demuxer->stream;
102 int64_t current_pos;
103 mp_msg(MSGT_HEADER, MSGL_DBG2, "mp_seek(%p, %"PRId64", %d)\n",
104 stream, pos, whence);
105 if (whence == SEEK_CUR)
106 pos += stream_tell(stream);
107 else if (whence == SEEK_END && stream->end_pos > 0)
108 pos += stream->end_pos;
109 else if (whence == SEEK_SET)
110 pos += stream->start_pos;
111 else if (whence == AVSEEK_SIZE && stream->end_pos > 0) {
112 off_t size;
113 if (stream_control(stream, STREAM_CTRL_GET_SIZE, &size) == STREAM_OK)
114 return size;
115 return stream->end_pos - stream->start_pos;
116 } else
117 return -1;
119 if (pos < 0)
120 return -1;
121 current_pos = stream_tell(stream);
122 if (stream_seek(stream, pos) == 0) {
123 stream_reset(stream);
124 stream_seek(stream, current_pos);
125 return -1;
128 return pos - stream->start_pos;
131 static int64_t mp_read_seek(void *opaque, int stream_idx, int64_t ts, int flags)
133 struct demuxer *demuxer = opaque;
134 struct stream *stream = demuxer->stream;
135 struct lavf_priv *priv = demuxer->priv;
137 AVStream *st = priv->avfc->streams[stream_idx];
138 double pts = (double)ts * st->time_base.num / st->time_base.den;
139 int ret = stream_control(stream, STREAM_CTRL_SEEK_TO_TIME, &pts);
140 if (ret < 0)
141 ret = AVERROR(ENOSYS);
142 return ret;
145 static void list_formats(void)
147 mp_msg(MSGT_DEMUX, MSGL_INFO, "Available lavf input formats:\n");
148 AVInputFormat *fmt = NULL;
149 while ((fmt = av_iformat_next(fmt)))
150 mp_msg(MSGT_DEMUX, MSGL_INFO, "%15s : %s\n", fmt->name, fmt->long_name);
153 static int lavf_check_file(demuxer_t *demuxer)
155 struct MPOpts *opts = demuxer->opts;
156 struct lavfdopts *lavfdopts = &opts->lavfdopts;
157 AVProbeData avpd;
158 lavf_priv_t *priv;
159 int probe_data_size = 0;
160 int read_size = INITIAL_PROBE_SIZE;
161 int score;
163 if (!demuxer->priv)
164 demuxer->priv = calloc(sizeof(lavf_priv_t), 1);
165 priv = demuxer->priv;
167 char *format = lavfdopts->format;
168 if (!format)
169 format = demuxer->stream->lavf_type;
170 if (format) {
171 if (strcmp(format, "help") == 0) {
172 list_formats();
173 return 0;
175 priv->avif = av_find_input_format(format);
176 if (!priv->avif) {
177 mp_msg(MSGT_DEMUX, MSGL_FATAL, "Unknown lavf format %s\n", format);
178 return 0;
180 mp_msg(MSGT_DEMUX, MSGL_INFO, "Forced lavf %s demuxer\n",
181 priv->avif->long_name);
182 return DEMUXER_TYPE_LAVF;
185 avpd.buf = av_mallocz(FFMAX(BIO_BUFFER_SIZE, PROBE_BUF_SIZE) +
186 FF_INPUT_BUFFER_PADDING_SIZE);
187 do {
188 read_size = stream_read(demuxer->stream, avpd.buf + probe_data_size,
189 read_size);
190 if (read_size < 0) {
191 av_free(avpd.buf);
192 return 0;
194 probe_data_size += read_size;
195 avpd.filename = demuxer->stream->url;
196 if (!avpd.filename) {
197 mp_msg(MSGT_DEMUX, MSGL_WARN, "Stream url is not set!\n");
198 avpd.filename = "";
200 if (!strncmp(avpd.filename, "ffmpeg://", 9) ||
201 !strncmp(avpd.filename, "lavf://", 7))
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 NULL
251 static int lavf_check_preferred_file(demuxer_t *demuxer)
253 if (lavf_check_file(demuxer)) {
254 const char * const *p;
255 lavf_priv_t *priv = demuxer->priv;
256 for (p = preferred_internal; *p; p++)
257 if (matches_avinputformat_name(priv, *p))
258 return 0;
259 return DEMUXER_TYPE_LAVF_PREFERRED;
261 return 0;
264 static uint8_t char2int(char c)
266 if (c >= '0' && c <= '9') return c - '0';
267 if (c >= 'a' && c <= 'f') return c - 'a' + 10;
268 if (c >= 'A' && c <= 'F') return c - 'A' + 10;
269 return 0;
272 static void parse_cryptokey(AVFormatContext *avfc, const char *str)
274 int len = strlen(str) / 2;
275 uint8_t *key = av_mallocz(len);
276 int i;
277 avfc->keylen = len;
278 avfc->key = key;
279 for (i = 0; i < len; i++, str += 2)
280 *key++ = (char2int(str[0]) << 4) | char2int(str[1]);
283 static void handle_stream(demuxer_t *demuxer, AVFormatContext *avfc, int i)
285 lavf_priv_t *priv = demuxer->priv;
286 AVStream *st = avfc->streams[i];
287 AVCodecContext *codec = st->codec;
288 char *stream_type = NULL;
289 int stream_id;
290 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL, 0);
291 AVDictionaryEntry *title = av_dict_get(st->metadata, "title", NULL, 0);
292 // Don't use native MPEG codec tag values with our generic tag tables.
293 // May contain for example value 3 for MP3, which we'd map to PCM audio.
294 if (matches_avinputformat_name(priv, "mpeg") ||
295 matches_avinputformat_name(priv, "mpegts"))
296 codec->codec_tag = 0;
297 int override_tag = mp_taglist_override(codec->codec_id);
298 // For some formats (like PCM) always trust CODEC_ID_* more than codec_tag
299 if (override_tag)
300 codec->codec_tag = override_tag;
302 switch (codec->codec_type) {
303 case AVMEDIA_TYPE_AUDIO: {
304 WAVEFORMATEX *wf;
305 sh_audio_t *sh_audio;
306 sh_audio = new_sh_audio_aid(demuxer, i, priv->audio_streams);
307 if (!sh_audio)
308 break;
309 stream_type = "audio";
310 priv->astreams[priv->audio_streams] = i;
311 sh_audio->libav_codec_id = codec->codec_id;
312 wf = calloc(sizeof(*wf) + codec->extradata_size, 1);
313 // mp4a tag is used for all mp4 files no matter what they actually contain
314 if (codec->codec_tag == MKTAG('m', 'p', '4', 'a'))
315 codec->codec_tag = 0;
316 if (!codec->codec_tag)
317 codec->codec_tag = mp_taglist_audio(codec->codec_id);
318 if (!codec->codec_tag)
319 codec->codec_tag = -1;
320 wf->wFormatTag = codec->codec_tag;
321 wf->nChannels = codec->channels;
322 wf->nSamplesPerSec = codec->sample_rate;
323 wf->nAvgBytesPerSec = codec->bit_rate / 8;
324 wf->nBlockAlign = codec->block_align ? codec->block_align : 1;
325 wf->wBitsPerSample = codec->bits_per_coded_sample;
326 wf->cbSize = codec->extradata_size;
327 if (codec->extradata_size)
328 memcpy(wf + 1, codec->extradata, codec->extradata_size);
329 sh_audio->wf = wf;
330 sh_audio->audio.dwSampleSize = codec->block_align;
331 if (codec->frame_size && codec->sample_rate) {
332 sh_audio->audio.dwScale = codec->frame_size;
333 sh_audio->audio.dwRate = codec->sample_rate;
334 } else {
335 sh_audio->audio.dwScale = codec->block_align ? codec->block_align * 8 : 8;
336 sh_audio->audio.dwRate = codec->bit_rate;
338 int g = av_gcd(sh_audio->audio.dwScale, sh_audio->audio.dwRate);
339 sh_audio->audio.dwScale /= g;
340 sh_audio->audio.dwRate /= g;
341 // 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);
342 sh_audio->ds = demuxer->audio;
343 sh_audio->format = codec->codec_tag;
344 sh_audio->channels = codec->channels;
345 sh_audio->samplerate = codec->sample_rate;
346 sh_audio->i_bps = codec->bit_rate / 8;
347 switch (codec->codec_id) {
348 case CODEC_ID_PCM_S8:
349 case CODEC_ID_PCM_U8:
350 sh_audio->samplesize = 1;
351 break;
352 case CODEC_ID_PCM_S16LE:
353 case CODEC_ID_PCM_S16BE:
354 case CODEC_ID_PCM_U16LE:
355 case CODEC_ID_PCM_U16BE:
356 sh_audio->samplesize = 2;
357 break;
358 case CODEC_ID_PCM_ALAW:
359 sh_audio->format = 0x6;
360 break;
361 case CODEC_ID_PCM_MULAW:
362 sh_audio->format = 0x7;
363 break;
365 if (title && title->value) {
366 sh_audio->title = talloc_strdup(sh_audio, title->value);
367 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AID_%d_NAME=%s\n",
368 priv->audio_streams, title->value);
370 if (lang && lang->value) {
371 sh_audio->lang = talloc_strdup(sh_audio, lang->value);
372 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AID_%d_LANG=%s\n",
373 priv->audio_streams, sh_audio->lang);
375 if (st->disposition & AV_DISPOSITION_DEFAULT)
376 sh_audio->default_track = 1;
377 if (mp_msg_test(MSGT_HEADER, MSGL_V))
378 print_wave_header(sh_audio->wf, MSGL_V);
379 st->discard = AVDISCARD_ALL;
380 stream_id = priv->audio_streams++;
381 break;
383 case AVMEDIA_TYPE_VIDEO: {
384 sh_video_t *sh_video;
385 BITMAPINFOHEADER *bih;
386 sh_video = new_sh_video_vid(demuxer, i, priv->video_streams);
387 if (!sh_video)
388 break;
389 stream_type = "video";
390 priv->vstreams[priv->video_streams] = i;
391 sh_video->libav_codec_id = codec->codec_id;
392 bih = calloc(sizeof(*bih) + codec->extradata_size, 1);
394 if (codec->codec_id == CODEC_ID_RAWVIDEO) {
395 switch (codec->pix_fmt) {
396 case PIX_FMT_RGB24:
397 codec->codec_tag = MKTAG(24, 'B', 'G', 'R');
398 case PIX_FMT_BGR24:
399 codec->codec_tag = MKTAG(24, 'R', 'G', 'B');
401 if (!codec->codec_tag)
402 codec->codec_tag = avcodec_pix_fmt_to_codec_tag(codec->pix_fmt);
403 } else if (!codec->codec_tag) {
404 codec->codec_tag = mp_taglist_video(codec->codec_id);
405 /* 0 might mean either unset or rawvideo; if codec_id
406 * was not RAWVIDEO assume it's unset
408 if (!codec->codec_tag)
409 codec->codec_tag = -1;
411 bih->biSize = sizeof(*bih) + codec->extradata_size;
412 bih->biWidth = codec->width;
413 bih->biHeight = codec->height;
414 bih->biBitCount = codec->bits_per_coded_sample;
415 bih->biSizeImage = bih->biWidth * bih->biHeight * bih->biBitCount / 8;
416 bih->biCompression = codec->codec_tag;
417 sh_video->bih = bih;
418 sh_video->disp_w = codec->width;
419 sh_video->disp_h = codec->height;
420 if (st->time_base.den) { /* if container has time_base, use that */
421 sh_video->video.dwRate = st->time_base.den;
422 sh_video->video.dwScale = st->time_base.num;
423 } else {
424 sh_video->video.dwRate = codec->time_base.den;
425 sh_video->video.dwScale = codec->time_base.num;
427 /* Try to make up some frame rate value, even if it's not reliable.
428 * FPS information is needed to support subtitle formats which base
429 * timing on frame numbers.
430 * Libavformat seems to report no "reliable" FPS value for AVI files,
431 * while they are typically constant enough FPS that the value this
432 * heuristic makes up works with subtitles in practice.
434 double fps;
435 if (st->r_frame_rate.num)
436 fps = av_q2d(st->r_frame_rate);
437 else
438 fps = 1.0 / FFMAX(av_q2d(st->time_base),
439 av_q2d(st->codec->time_base) *
440 st->codec->ticks_per_frame);
441 sh_video->fps = fps;
442 sh_video->frametime = 1 / fps;
443 sh_video->format = bih->biCompression;
444 if (st->sample_aspect_ratio.num)
445 sh_video->aspect = codec->width * st->sample_aspect_ratio.num
446 / (float)(codec->height * st->sample_aspect_ratio.den);
447 else
448 sh_video->aspect = codec->width * codec->sample_aspect_ratio.num
449 / (float)(codec->height * codec->sample_aspect_ratio.den);
450 sh_video->i_bps = codec->bit_rate / 8;
451 if (title && title->value) {
452 sh_video->title = talloc_strdup(sh_video, title->value);
453 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VID_%d_NAME=%s\n",
454 priv->video_streams, title->value);
456 mp_msg(MSGT_DEMUX, MSGL_DBG2, "aspect= %d*%d/(%d*%d)\n",
457 codec->width, codec->sample_aspect_ratio.num,
458 codec->height, codec->sample_aspect_ratio.den);
460 sh_video->ds = demuxer->video;
461 if (codec->extradata_size)
462 memcpy(sh_video->bih + 1, codec->extradata, codec->extradata_size);
463 if ( mp_msg_test(MSGT_HEADER, MSGL_V))
464 print_video_header(sh_video->bih, MSGL_V);
465 st->discard = AVDISCARD_ALL;
466 stream_id = priv->video_streams++;
467 break;
469 case AVMEDIA_TYPE_SUBTITLE: {
470 sh_sub_t *sh_sub;
471 char type;
472 /* only support text subtitles for now */
473 if (codec->codec_id == CODEC_ID_TEXT)
474 type = 't';
475 else if (codec->codec_id == CODEC_ID_MOV_TEXT)
476 type = 'm';
477 else if (codec->codec_id == CODEC_ID_SSA)
478 type = 'a';
479 else if (codec->codec_id == CODEC_ID_DVD_SUBTITLE)
480 type = 'v';
481 else if (codec->codec_id == CODEC_ID_XSUB)
482 type = 'x';
483 else if (codec->codec_id == CODEC_ID_DVB_SUBTITLE)
484 type = 'b';
485 else if (codec->codec_id == CODEC_ID_DVB_TELETEXT)
486 type = 'd';
487 else if (codec->codec_id == CODEC_ID_HDMV_PGS_SUBTITLE)
488 type = 'p';
489 else
490 break;
491 sh_sub = new_sh_sub_sid(demuxer, i, priv->sub_streams);
492 if (!sh_sub)
493 break;
494 stream_type = "subtitle";
495 priv->sstreams[priv->sub_streams] = i;
496 sh_sub->libav_codec_id = codec->codec_id;
497 sh_sub->type = type;
498 if (codec->extradata_size) {
499 sh_sub->extradata = malloc(codec->extradata_size);
500 memcpy(sh_sub->extradata, codec->extradata, codec->extradata_size);
501 sh_sub->extradata_len = codec->extradata_size;
503 if (title && title->value) {
504 sh_sub->title = talloc_strdup(sh_sub, title->value);
505 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SID_%d_NAME=%s\n",
506 priv->sub_streams, title->value);
508 if (lang && lang->value) {
509 sh_sub->lang = talloc_strdup(sh_sub, lang->value);
510 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SID_%d_LANG=%s\n",
511 priv->sub_streams, sh_sub->lang);
513 if (st->disposition & AV_DISPOSITION_DEFAULT)
514 sh_sub->default_track = 1;
515 stream_id = priv->sub_streams++;
516 break;
518 case AVMEDIA_TYPE_ATTACHMENT: {
519 AVDictionaryEntry *ftag = av_dict_get(st->metadata, "filename",
520 NULL, 0);
521 char *filename = ftag ? ftag->value : NULL;
522 if (st->codec->codec_id == CODEC_ID_TTF)
523 demuxer_add_attachment(demuxer, bstr(filename),
524 bstr("application/x-truetype-font"),
525 (struct bstr){codec->extradata,
526 codec->extradata_size});
527 break;
529 default:
530 st->discard = AVDISCARD_ALL;
532 if (stream_type) {
533 AVCodec *avc = avcodec_find_decoder(codec->codec_id);
534 const char *codec_name = avc ? avc->name : "unknown";
535 if (!avc && *stream_type == 's' && demuxer->s_streams[i])
536 codec_name = sh_sub_type2str((demuxer->s_streams[i])->type);
537 mp_msg(MSGT_DEMUX, MSGL_INFO, "[lavf] stream %d: %s (%s), -%cid %d",
538 i, stream_type, codec_name, *stream_type, stream_id);
539 if (lang && lang->value && *stream_type != 'v')
540 mp_msg(MSGT_DEMUX, MSGL_INFO, ", -%clang %s",
541 *stream_type, lang->value);
542 if (title && title->value)
543 mp_msg(MSGT_DEMUX, MSGL_INFO, ", %s", title->value);
544 mp_msg(MSGT_DEMUX, MSGL_INFO, "\n");
548 static demuxer_t *demux_open_lavf(demuxer_t *demuxer)
550 struct MPOpts *opts = demuxer->opts;
551 struct lavfdopts *lavfdopts = &opts->lavfdopts;
552 AVFormatContext *avfc;
553 AVDictionaryEntry *t = NULL;
554 lavf_priv_t *priv = demuxer->priv;
555 int i;
556 char mp_filename[256] = "mp:";
558 stream_seek(demuxer->stream, 0);
560 avfc = avformat_alloc_context();
562 if (lavfdopts->cryptokey)
563 parse_cryptokey(avfc, lavfdopts->cryptokey);
564 if (matches_avinputformat_name(priv, "avi")) {
565 /* for avi libavformat returns the avi timestamps in .dts,
566 * some made-up stuff that's not really pts in .pts */
567 priv->use_dts = true;
568 demuxer->timestamp_type = TIMESTAMP_TYPE_SORT;
569 } else {
570 if (opts->user_correct_pts != 0)
571 avfc->flags |= AVFMT_FLAG_GENPTS;
573 if (index_mode == 0)
574 avfc->flags |= AVFMT_FLAG_IGNIDX;
576 if (lavfdopts->probesize) {
577 if (av_opt_set_int(avfc, "probesize", lavfdopts->probesize, 0) < 0)
578 mp_msg(MSGT_HEADER, MSGL_ERR,
579 "demux_lavf, couldn't set option probesize to %u\n",
580 lavfdopts->probesize);
582 if (lavfdopts->analyzeduration) {
583 if (av_opt_set_int(avfc, "analyzeduration",
584 lavfdopts->analyzeduration * AV_TIME_BASE, 0) < 0)
585 mp_msg(MSGT_HEADER, MSGL_ERR, "demux_lavf, couldn't set option "
586 "analyzeduration to %u\n", lavfdopts->analyzeduration);
589 if (lavfdopts->avopt) {
590 if (parse_avopts(avfc, lavfdopts->avopt) < 0) {
591 mp_msg(MSGT_HEADER, MSGL_ERR,
592 "Your options /%s/ look like gibberish to me pal\n",
593 lavfdopts->avopt);
594 return NULL;
598 if (demuxer->stream->url) {
599 if (demuxer->stream->lavf_type && !strcmp(demuxer->stream->lavf_type,
600 "rtsp")) {
601 // Remove possible leading ffmpeg:// or lavf://
602 char *name = strstr(demuxer->stream->url, "rtsp:");
603 av_strlcpy(mp_filename, name, sizeof(mp_filename));
604 } else
605 av_strlcat(mp_filename, demuxer->stream->url, sizeof(mp_filename));
606 } else
607 av_strlcat(mp_filename, "foobar.dummy", sizeof(mp_filename));
609 if (!(priv->avif->flags & AVFMT_NOFILE)) {
610 priv->pb = avio_alloc_context(priv->buffer, BIO_BUFFER_SIZE, 0,
611 demuxer, mp_read, NULL, mp_seek);
612 priv->pb->read_seek = mp_read_seek;
613 priv->pb->seekable = demuxer->stream->end_pos
614 && (demuxer->stream->flags & MP_STREAM_SEEK) == MP_STREAM_SEEK
615 ? AVIO_SEEKABLE_NORMAL : 0;
616 avfc->pb = priv->pb;
619 if (avformat_open_input(&avfc, mp_filename, priv->avif, NULL) < 0) {
620 mp_msg(MSGT_HEADER, MSGL_ERR,
621 "LAVF_header: avformat_open_input() failed\n");
622 return NULL;
625 priv->avfc = avfc;
627 if (avformat_find_stream_info(avfc, NULL) < 0) {
628 mp_msg(MSGT_HEADER, MSGL_ERR,
629 "LAVF_header: av_find_stream_info() failed\n");
630 return NULL;
633 /* Add metadata. */
634 while ((t = av_dict_get(avfc->metadata, "", t,
635 AV_DICT_IGNORE_SUFFIX)))
636 demux_info_add(demuxer, t->key, t->value);
638 for (i = 0; i < avfc->nb_chapters; i++) {
639 AVChapter *c = avfc->chapters[i];
640 uint64_t start = av_rescale_q(c->start, c->time_base,
641 (AVRational){1, 1000000000});
642 uint64_t end = av_rescale_q(c->end, c->time_base,
643 (AVRational){1, 1000000000});
644 t = av_dict_get(c->metadata, "title", NULL, 0);
645 demuxer_add_chapter(demuxer, t ? bstr(t->value) : bstr(NULL),
646 start, end);
649 for (i = 0; i < avfc->nb_streams; i++)
650 handle_stream(demuxer, avfc, i);
651 priv->nb_streams_last = avfc->nb_streams;
653 if (avfc->nb_programs) {
654 int p;
655 for (p = 0; p < avfc->nb_programs; p++) {
656 AVProgram *program = avfc->programs[p];
657 t = av_dict_get(program->metadata, "title", NULL, 0);
658 mp_msg(MSGT_HEADER, MSGL_INFO, "LAVF: Program %d %s\n",
659 program->id, t ? t->value : "");
660 mp_msg(MSGT_IDENTIFY, MSGL_V, "PROGRAM_ID=%d\n", program->id);
664 mp_msg(MSGT_HEADER, MSGL_V, "LAVF: %d audio and %d video streams found\n",
665 priv->audio_streams, priv->video_streams);
666 demuxer->audio->id = -2; // wait for higher-level code to select track
667 /* There's still no global video track selection, so we have to pick
668 * the default video track in the demuxer.
669 * Note that the interface doesn't make sense: demuxer->video->id
670 * is initialized to --vid value, but after demuxer initialization
671 * it contains either -2 for disabled or v_streams[] index. */
672 int vid = demuxer->video->id;
673 demuxer->video->id = -2;
674 demuxer->desc->control(demuxer, DEMUXER_CTRL_SWITCH_VIDEO, &vid);
675 if (demuxer->video->id >= 0)
676 demuxer->video->sh = demuxer->v_streams[demuxer->video->id];
678 // disabled because unreliable per-stream bitrate values returned
679 // by libavformat trigger this heuristic incorrectly and break things
680 #if 0
681 /* libavformat sets bitrate for mpeg based on pts at start and end
682 * of file, which fails for files with pts resets. So calculate our
683 * own bitrate estimate. */
684 if (priv->avif->flags & AVFMT_TS_DISCONT) {
685 for (int i = 0; i < avfc->nb_streams; i++)
686 priv->bitrate += avfc->streams[i]->codec->bit_rate;
687 /* pts-based is more accurate if there are no resets; try to make
688 * a somewhat reasonable guess */
689 if (!avfc->duration || avfc->duration == AV_NOPTS_VALUE
690 || priv->bitrate && (avfc->bit_rate < priv->bitrate / 2
691 || avfc->bit_rate > priv->bitrate * 2))
692 priv->seek_by_bytes = true;
693 if (!priv->bitrate)
694 priv->bitrate = 1440000;
696 #endif
697 demuxer->accurate_seek = !priv->seek_by_bytes;
699 return demuxer;
702 static void check_internet_radio_hack(struct demuxer *demuxer)
704 struct lavf_priv *priv = demuxer->priv;
705 struct AVFormatContext *avfc = priv->avfc;
707 if (!matches_avinputformat_name(priv, "ogg"))
708 return;
709 if (priv->nb_streams_last == avfc->nb_streams)
710 return;
711 if (avfc->nb_streams - priv->nb_streams_last == 1
712 && priv->video_streams == 0 && priv->sub_streams == 0
713 && demuxer->a_streams[priv->audio_streams - 1]->format == 0x566f // vorbis
714 && (priv->audio_streams == 2 || priv->internet_radio_hack)
715 && demuxer->a_streams[0]->format == 0x566f) {
716 // extradata match could be checked but would require parsing
717 // headers, as the comment section will vary
718 if (!priv->internet_radio_hack) {
719 mp_msg(MSGT_DEMUX, MSGL_V,
720 "[lavf] enabling internet ogg radio hack\n");
722 priv->internet_radio_hack = true;
723 // use new per-track metadata as global metadata
724 AVDictionaryEntry *t = NULL;
725 AVStream *stream = avfc->streams[avfc->nb_streams - 1];
726 while ((t = av_dict_get(stream->metadata, "", t,
727 AV_DICT_IGNORE_SUFFIX)))
728 demux_info_add(demuxer, t->key, t->value);
729 } else {
730 if (priv->internet_radio_hack)
731 mp_tmsg(MSGT_DEMUX, MSGL_WARN, "[lavf] Internet radio ogg hack "
732 "was enabled, but stream characteristics changed.\n"
733 "This may or may not work.\n");
734 priv->internet_radio_hack = false;
738 static int destroy_avpacket(void *pkt)
740 av_free_packet(pkt);
741 return 0;
744 static int demux_lavf_fill_buffer(demuxer_t *demux, demux_stream_t *dsds)
746 lavf_priv_t *priv = demux->priv;
747 demux_packet_t *dp;
748 demux_stream_t *ds;
749 int id;
750 mp_msg(MSGT_DEMUX, MSGL_DBG2, "demux_lavf_fill_buffer()\n");
752 demux->filepos = stream_tell(demux->stream);
754 AVPacket *pkt = talloc(NULL, AVPacket);
755 if (av_read_frame(priv->avfc, pkt) < 0) {
756 talloc_free(pkt);
757 return 0;
759 talloc_set_destructor(pkt, destroy_avpacket);
761 // handle any new streams that might have been added
762 for (id = priv->nb_streams_last; id < priv->avfc->nb_streams; id++)
763 handle_stream(demux, priv->avfc, id);
764 check_internet_radio_hack(demux);
766 priv->nb_streams_last = priv->avfc->nb_streams;
768 id = pkt->stream_index;
770 if (id == demux->audio->id || priv->internet_radio_hack) {
771 // audio
772 ds = demux->audio;
773 } else if (id == demux->video->id) {
774 // video
775 ds = demux->video;
776 } else if (id == demux->sub->id) {
777 // subtitle
778 ds = demux->sub;
779 } else {
780 talloc_free(pkt);
781 return 1;
784 // If the packet has pointers to temporary fields that could be
785 // overwritten/freed by next av_read_frame(), copy them to persistent
786 // allocations so we can safely queue the packet for any length of time.
787 if (av_dup_packet(pkt) < 0)
788 abort();
789 dp = new_demux_packet_fromdata(pkt->data, pkt->size);
790 dp->avpacket = pkt;
792 int64_t ts = priv->use_dts ? pkt->dts : pkt->pts;
793 if (ts != AV_NOPTS_VALUE) {
794 dp->pts = ts * av_q2d(priv->avfc->streams[id]->time_base);
795 priv->last_pts = dp->pts * AV_TIME_BASE;
796 // always set duration for subtitles, even if AV_PKT_FLAG_KEY isn't set,
797 // otherwise they will stay on screen to long if e.g. ASS is demuxed
798 // from mkv
799 if ((ds == demux->sub || (pkt->flags & AV_PKT_FLAG_KEY)) &&
800 pkt->convergence_duration > 0)
801 dp->duration = pkt->convergence_duration *
802 av_q2d(priv->avfc->streams[id]->time_base);
804 dp->pos = demux->filepos;
805 dp->keyframe = pkt->flags & AV_PKT_FLAG_KEY;
806 // append packet to DS stream:
807 ds_add_packet(ds, dp);
808 return 1;
811 static void demux_seek_lavf(demuxer_t *demuxer, float rel_seek_secs,
812 float audio_delay, int flags)
814 lavf_priv_t *priv = demuxer->priv;
815 int avsflags = 0;
816 mp_msg(MSGT_DEMUX, MSGL_DBG2, "demux_seek_lavf(%p, %f, %f, %d)\n",
817 demuxer, rel_seek_secs, audio_delay, flags);
819 if (priv->seek_by_bytes) {
820 int64_t pos = demuxer->filepos;
821 rel_seek_secs *= priv->bitrate / 8;
822 pos += rel_seek_secs;
823 av_seek_frame(priv->avfc, -1, pos, AVSEEK_FLAG_BYTE);
824 return;
827 if (flags & SEEK_ABSOLUTE)
828 priv->last_pts = 0;
829 else if (rel_seek_secs < 0)
830 avsflags = AVSEEK_FLAG_BACKWARD;
831 if (flags & SEEK_FORWARD)
832 avsflags = 0;
833 else if (flags & SEEK_BACKWARD)
834 avsflags = AVSEEK_FLAG_BACKWARD;
835 if (flags & SEEK_FACTOR) {
836 if (priv->avfc->duration == 0 || priv->avfc->duration == AV_NOPTS_VALUE)
837 return;
838 priv->last_pts += rel_seek_secs * priv->avfc->duration;
839 } else
840 priv->last_pts += rel_seek_secs * AV_TIME_BASE;
841 if (av_seek_frame(priv->avfc, -1, priv->last_pts, avsflags) < 0) {
842 avsflags ^= AVSEEK_FLAG_BACKWARD;
843 av_seek_frame(priv->avfc, -1, priv->last_pts, avsflags);
847 static int demux_lavf_control(demuxer_t *demuxer, int cmd, void *arg)
849 lavf_priv_t *priv = demuxer->priv;
851 switch (cmd) {
852 case DEMUXER_CTRL_CORRECT_PTS:
853 return DEMUXER_CTRL_OK;
854 case DEMUXER_CTRL_GET_TIME_LENGTH:
855 if (priv->seek_by_bytes) {
856 /* Our bitrate estimate may be better than would be used in
857 * otherwise similar fallback code at higher level */
858 if (demuxer->movi_end <= 0)
859 return DEMUXER_CTRL_DONTKNOW;
860 *(double *)arg = (demuxer->movi_end - demuxer->movi_start) * 8 /
861 priv->bitrate;
862 return DEMUXER_CTRL_GUESS;
864 if (priv->avfc->duration == 0 || priv->avfc->duration == AV_NOPTS_VALUE)
865 return DEMUXER_CTRL_DONTKNOW;
867 *((double *)arg) = (double)priv->avfc->duration / AV_TIME_BASE;
868 return DEMUXER_CTRL_OK;
870 case DEMUXER_CTRL_GET_PERCENT_POS:
871 if (priv->seek_by_bytes)
872 return DEMUXER_CTRL_DONTKNOW; // let it use the fallback code
873 if (priv->avfc->duration == 0 || priv->avfc->duration == AV_NOPTS_VALUE)
874 return DEMUXER_CTRL_DONTKNOW;
876 *((int *)arg) = (int)((priv->last_pts - priv->avfc->start_time) * 100 /
877 priv->avfc->duration);
878 return DEMUXER_CTRL_OK;
879 case DEMUXER_CTRL_SWITCH_AUDIO:
880 case DEMUXER_CTRL_SWITCH_VIDEO:
882 int id = *((int *)arg);
883 int newid = -2;
884 int i, curridx = -1;
885 int nstreams, *pstreams;
886 demux_stream_t *ds;
888 if (cmd == DEMUXER_CTRL_SWITCH_VIDEO) {
889 ds = demuxer->video;
890 nstreams = priv->video_streams;
891 pstreams = priv->vstreams;
892 } else {
893 ds = demuxer->audio;
894 nstreams = priv->audio_streams;
895 pstreams = priv->astreams;
897 for (i = 0; i < nstreams; i++) {
898 if (pstreams[i] == ds->id) { //current stream id
899 curridx = i;
900 break;
904 if (id == -1) { // next track
905 i = (curridx + 2) % (nstreams + 1) - 1;
906 if (i >= 0)
907 newid = pstreams[i];
908 } else if (id >= 0 && id < nstreams) { // select track by id
909 i = id;
910 newid = pstreams[i];
911 } else // no sound
912 i = -1;
914 if (i == curridx) {
915 *(int *) arg = curridx < 0 ? -2 : curridx;
916 return DEMUXER_CTRL_OK;
917 } else {
918 ds_free_packs(ds);
919 if (ds->id >= 0)
920 priv->avfc->streams[ds->id]->discard = AVDISCARD_ALL;
921 ds->id = newid;
922 *(int *) arg = i < 0 ? -2 : i;
923 if (newid >= 0)
924 priv->avfc->streams[newid]->discard = AVDISCARD_NONE;
925 return DEMUXER_CTRL_OK;
928 case DEMUXER_CTRL_IDENTIFY_PROGRAM:
930 demux_program_t *prog = arg;
931 AVProgram *program;
932 int p, i;
933 int start;
935 prog->vid = prog->aid = prog->sid = -2;
936 if (priv->avfc->nb_programs < 1)
937 return DEMUXER_CTRL_DONTKNOW;
939 if (prog->progid == -1) {
940 p = 0;
941 while (p < priv->avfc->nb_programs && priv->avfc->programs[p]->id != priv->cur_program)
942 p++;
943 p = (p + 1) % priv->avfc->nb_programs;
944 } else {
945 for (i = 0; i < priv->avfc->nb_programs; i++)
946 if (priv->avfc->programs[i]->id == prog->progid)
947 break;
948 if (i == priv->avfc->nb_programs)
949 return DEMUXER_CTRL_DONTKNOW;
950 p = i;
952 start = p;
953 redo:
954 program = priv->avfc->programs[p];
955 for (i = 0; i < program->nb_stream_indexes; i++) {
956 switch (priv->avfc->streams[program->stream_index[i]]->codec->codec_type) {
957 case AVMEDIA_TYPE_VIDEO:
958 if (prog->vid == -2)
959 prog->vid = program->stream_index[i];
960 break;
961 case AVMEDIA_TYPE_AUDIO:
962 if (prog->aid == -2)
963 prog->aid = program->stream_index[i];
964 break;
965 case AVMEDIA_TYPE_SUBTITLE:
966 if (prog->sid == -2 && priv->avfc->streams[program->stream_index[i]]->codec->codec_id == CODEC_ID_TEXT)
967 prog->sid = program->stream_index[i];
968 break;
971 if (prog->aid >= 0 && prog->aid < MAX_A_STREAMS &&
972 demuxer->a_streams[prog->aid]) {
973 sh_audio_t *sh = demuxer->a_streams[prog->aid];
974 prog->aid = sh->aid;
975 } else
976 prog->aid = -2;
977 if (prog->vid >= 0 && prog->vid < MAX_V_STREAMS &&
978 demuxer->v_streams[prog->vid]) {
979 sh_video_t *sh = demuxer->v_streams[prog->vid];
980 prog->vid = sh->vid;
981 } else
982 prog->vid = -2;
983 if (prog->progid == -1 && prog->vid == -2 && prog->aid == -2) {
984 p = (p + 1) % priv->avfc->nb_programs;
985 if (p == start)
986 return DEMUXER_CTRL_DONTKNOW;
987 goto redo;
989 priv->cur_program = prog->progid = program->id;
990 return DEMUXER_CTRL_OK;
992 default:
993 return DEMUXER_CTRL_NOTIMPL;
997 static void demux_close_lavf(demuxer_t *demuxer)
999 lavf_priv_t *priv = demuxer->priv;
1000 if (priv) {
1001 if (priv->avfc) {
1002 av_freep(&priv->avfc->key);
1003 avformat_close_input(&priv->avfc);
1005 av_freep(&priv->pb);
1006 free(priv);
1007 demuxer->priv = NULL;
1012 const demuxer_desc_t demuxer_desc_lavf = {
1013 "libavformat demuxer",
1014 "lavf",
1015 "libavformat",
1016 "Michael Niedermayer",
1017 "supports many formats, requires libavformat",
1018 DEMUXER_TYPE_LAVF,
1019 0, // Check after other demuxer
1020 lavf_check_file,
1021 demux_lavf_fill_buffer,
1022 demux_open_lavf,
1023 demux_close_lavf,
1024 demux_seek_lavf,
1025 demux_lavf_control
1028 const demuxer_desc_t demuxer_desc_lavf_preferred = {
1029 "libavformat preferred demuxer",
1030 "lavfpref",
1031 "libavformat",
1032 "Michael Niedermayer",
1033 "supports many formats, requires libavformat",
1034 DEMUXER_TYPE_LAVF_PREFERRED,
1036 lavf_check_preferred_file,
1037 demux_lavf_fill_buffer,
1038 demux_open_lavf,
1039 demux_close_lavf,
1040 demux_seek_lavf,
1041 demux_lavf_control