ao_pulse: support native mute control
[mplayer.git] / libmpdemux / demux_lavf.c
blobf8311e215c975186042d2c5d05bfe0a843562e97
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 sh_video->fps = av_q2d(st->r_frame_rate);
421 sh_video->frametime = 1 / av_q2d(st->r_frame_rate);
422 sh_video->format = bih->biCompression;
423 if (st->sample_aspect_ratio.num)
424 sh_video->aspect = codec->width * st->sample_aspect_ratio.num
425 / (float)(codec->height * st->sample_aspect_ratio.den);
426 else
427 sh_video->aspect = codec->width * codec->sample_aspect_ratio.num
428 / (float)(codec->height * codec->sample_aspect_ratio.den);
429 sh_video->i_bps = codec->bit_rate / 8;
430 if (title && title->value) {
431 sh_video->title = talloc_strdup(sh_video, title->value);
432 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VID_%d_NAME=%s\n",
433 priv->video_streams, title->value);
435 mp_msg(MSGT_DEMUX, MSGL_DBG2, "aspect= %d*%d/(%d*%d)\n",
436 codec->width, codec->sample_aspect_ratio.num,
437 codec->height, codec->sample_aspect_ratio.den);
439 sh_video->ds = demuxer->video;
440 if (codec->extradata_size)
441 memcpy(sh_video->bih + 1, codec->extradata, codec->extradata_size);
442 if ( mp_msg_test(MSGT_HEADER, MSGL_V))
443 print_video_header(sh_video->bih, MSGL_V);
444 if (demuxer->video->id != priv->video_streams
445 && demuxer->video->id != -1)
446 st->discard = AVDISCARD_ALL;
447 else {
448 demuxer->video->id = i;
449 demuxer->video->sh = demuxer->v_streams[i];
451 stream_id = priv->video_streams++;
452 break;
454 case AVMEDIA_TYPE_SUBTITLE: {
455 sh_sub_t *sh_sub;
456 char type;
457 /* only support text subtitles for now */
458 if (codec->codec_id == CODEC_ID_TEXT)
459 type = 't';
460 else if (codec->codec_id == CODEC_ID_MOV_TEXT)
461 type = 'm';
462 else if (codec->codec_id == CODEC_ID_SSA)
463 type = 'a';
464 else if (codec->codec_id == CODEC_ID_DVD_SUBTITLE)
465 type = 'v';
466 else if (codec->codec_id == CODEC_ID_XSUB)
467 type = 'x';
468 else if (codec->codec_id == CODEC_ID_DVB_SUBTITLE)
469 type = 'b';
470 else if (codec->codec_id == CODEC_ID_DVB_TELETEXT)
471 type = 'd';
472 else if (codec->codec_id == CODEC_ID_HDMV_PGS_SUBTITLE)
473 type = 'p';
474 else
475 break;
476 sh_sub = new_sh_sub_sid(demuxer, i, priv->sub_streams);
477 if (!sh_sub)
478 break;
479 stream_type = "subtitle";
480 priv->sstreams[priv->sub_streams] = i;
481 sh_sub->type = type;
482 if (codec->extradata_size) {
483 sh_sub->extradata = malloc(codec->extradata_size);
484 memcpy(sh_sub->extradata, codec->extradata, codec->extradata_size);
485 sh_sub->extradata_len = codec->extradata_size;
487 if (title && title->value) {
488 sh_sub->title = talloc_strdup(sh_sub, title->value);
489 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SID_%d_NAME=%s\n",
490 priv->sub_streams, title->value);
492 if (lang && lang->value) {
493 sh_sub->lang = talloc_strdup(sh_sub, lang->value);
494 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SID_%d_LANG=%s\n",
495 priv->sub_streams, sh_sub->lang);
497 if (st->disposition & AV_DISPOSITION_DEFAULT)
498 sh_sub->default_track = 1;
499 stream_id = priv->sub_streams++;
500 break;
502 case AVMEDIA_TYPE_ATTACHMENT: {
503 AVDictionaryEntry *ftag = av_dict_get(st->metadata, "filename",
504 NULL, 0);
505 char *filename = ftag ? ftag->value : NULL;
506 if (st->codec->codec_id == CODEC_ID_TTF)
507 demuxer_add_attachment(demuxer, bstr(filename),
508 bstr("application/x-truetype-font"),
509 (struct bstr){codec->extradata,
510 codec->extradata_size});
511 break;
513 default:
514 st->discard = AVDISCARD_ALL;
516 if (stream_type) {
517 AVCodec *avc = avcodec_find_decoder(codec->codec_id);
518 const char *codec_name = avc ? avc->name : "unknown";
519 if (!avc && *stream_type == 's' && demuxer->s_streams[i])
520 codec_name = sh_sub_type2str((demuxer->s_streams[i])->type);
521 mp_msg(MSGT_DEMUX, MSGL_INFO, "[lavf] stream %d: %s (%s), -%cid %d",
522 i, stream_type, codec_name, *stream_type, stream_id);
523 if (lang && lang->value && *stream_type != 'v')
524 mp_msg(MSGT_DEMUX, MSGL_INFO, ", -%clang %s",
525 *stream_type, lang->value);
526 if (title && title->value)
527 mp_msg(MSGT_DEMUX, MSGL_INFO, ", %s", title->value);
528 mp_msg(MSGT_DEMUX, MSGL_INFO, "\n");
532 static demuxer_t *demux_open_lavf(demuxer_t *demuxer)
534 struct MPOpts *opts = demuxer->opts;
535 struct lavfdopts *lavfdopts = &opts->lavfdopts;
536 AVFormatContext *avfc;
537 AVDictionaryEntry *t = NULL;
538 lavf_priv_t *priv = demuxer->priv;
539 int i;
540 char mp_filename[256] = "mp:";
542 stream_seek(demuxer->stream, 0);
544 avfc = avformat_alloc_context();
546 if (lavfdopts->cryptokey)
547 parse_cryptokey(avfc, lavfdopts->cryptokey);
548 if (matches_avinputformat_name(priv, "avi")) {
549 /* for avi libavformat returns the avi timestamps in .dts,
550 * some made-up stuff that's not really pts in .pts */
551 priv->use_dts = true;
552 demuxer->timestamp_type = TIMESTAMP_TYPE_SORT;
553 } else {
554 if (opts->user_correct_pts != 0)
555 avfc->flags |= AVFMT_FLAG_GENPTS;
557 if (index_mode == 0)
558 avfc->flags |= AVFMT_FLAG_IGNIDX;
560 if (lavfdopts->probesize) {
561 if (av_opt_set_int(avfc, "probesize", lavfdopts->probesize, 0) < 0)
562 mp_msg(MSGT_HEADER, MSGL_ERR,
563 "demux_lavf, couldn't set option probesize to %u\n",
564 lavfdopts->probesize);
566 if (lavfdopts->analyzeduration) {
567 if (av_opt_set_int(avfc, "analyzeduration",
568 lavfdopts->analyzeduration * AV_TIME_BASE, 0) < 0)
569 mp_msg(MSGT_HEADER, MSGL_ERR, "demux_lavf, couldn't set option "
570 "analyzeduration to %u\n", lavfdopts->analyzeduration);
573 if (lavfdopts->avopt) {
574 if (parse_avopts(avfc, lavfdopts->avopt) < 0) {
575 mp_msg(MSGT_HEADER, MSGL_ERR,
576 "Your options /%s/ look like gibberish to me pal\n",
577 lavfdopts->avopt);
578 return NULL;
582 if (demuxer->stream->url) {
583 if (!strncmp(demuxer->stream->url, "ffmpeg://rtsp:", 14))
584 av_strlcpy(mp_filename, demuxer->stream->url + 9,
585 sizeof(mp_filename));
586 else
587 av_strlcat(mp_filename, demuxer->stream->url, sizeof(mp_filename));
588 } else
589 av_strlcat(mp_filename, "foobar.dummy", sizeof(mp_filename));
591 if (!(priv->avif->flags & AVFMT_NOFILE)) {
592 priv->pb = avio_alloc_context(priv->buffer, BIO_BUFFER_SIZE, 0,
593 demuxer, mp_read, NULL, mp_seek);
594 priv->pb->read_seek = mp_read_seek;
595 priv->pb->seekable = demuxer->stream->end_pos
596 && (demuxer->stream->flags & MP_STREAM_SEEK) == MP_STREAM_SEEK
597 ? AVIO_SEEKABLE_NORMAL : 0;
598 avfc->pb = priv->pb;
601 if (avformat_open_input(&avfc, mp_filename, priv->avif, NULL) < 0) {
602 mp_msg(MSGT_HEADER, MSGL_ERR,
603 "LAVF_header: avformat_open_input() failed\n");
604 return NULL;
607 priv->avfc = avfc;
609 if (avformat_find_stream_info(avfc, NULL) < 0) {
610 mp_msg(MSGT_HEADER, MSGL_ERR,
611 "LAVF_header: av_find_stream_info() failed\n");
612 return NULL;
615 /* Add metadata. */
616 while ((t = av_dict_get(avfc->metadata, "", t,
617 AV_DICT_IGNORE_SUFFIX)))
618 demux_info_add(demuxer, t->key, t->value);
620 for (i = 0; i < avfc->nb_chapters; i++) {
621 AVChapter *c = avfc->chapters[i];
622 uint64_t start = av_rescale_q(c->start, c->time_base,
623 (AVRational){1, 1000000000});
624 uint64_t end = av_rescale_q(c->end, c->time_base,
625 (AVRational){1, 1000000000});
626 t = av_dict_get(c->metadata, "title", NULL, 0);
627 demuxer_add_chapter(demuxer, t ? bstr(t->value) : bstr(NULL),
628 start, end);
631 for (i = 0; i < avfc->nb_streams; i++)
632 handle_stream(demuxer, avfc, i);
633 priv->nb_streams_last = avfc->nb_streams;
635 if (avfc->nb_programs) {
636 int p;
637 for (p = 0; p < avfc->nb_programs; p++) {
638 AVProgram *program = avfc->programs[p];
639 t = av_dict_get(program->metadata, "title", NULL, 0);
640 mp_msg(MSGT_HEADER, MSGL_INFO, "LAVF: Program %d %s\n",
641 program->id, t ? t->value : "");
642 mp_msg(MSGT_IDENTIFY, MSGL_V, "PROGRAM_ID=%d\n", program->id);
646 mp_msg(MSGT_HEADER, MSGL_V, "LAVF: %d audio and %d video streams found\n",
647 priv->audio_streams, priv->video_streams);
648 mp_msg(MSGT_HEADER, MSGL_V, "LAVF: build %d\n", LIBAVFORMAT_BUILD);
649 demuxer->audio->id = -2; // wait for higher-level code to select track
650 if (!priv->video_streams) {
651 if (!priv->audio_streams) {
652 mp_msg(MSGT_HEADER, MSGL_ERR,
653 "LAVF: no audio or video headers found - broken file?\n");
654 return NULL;
656 demuxer->video->id = -2; // audio-only
659 // disabled because unreliable per-stream bitrate values returned
660 // by libavformat trigger this heuristic incorrectly and break things
661 #if 0
662 /* libavformat sets bitrate for mpeg based on pts at start and end
663 * of file, which fails for files with pts resets. So calculate our
664 * own bitrate estimate. */
665 if (priv->avif->flags & AVFMT_TS_DISCONT) {
666 for (int i = 0; i < avfc->nb_streams; i++)
667 priv->bitrate += avfc->streams[i]->codec->bit_rate;
668 /* pts-based is more accurate if there are no resets; try to make
669 * a somewhat reasonable guess */
670 if (!avfc->duration || avfc->duration == AV_NOPTS_VALUE
671 || priv->bitrate && (avfc->bit_rate < priv->bitrate / 2
672 || avfc->bit_rate > priv->bitrate * 2))
673 priv->seek_by_bytes = true;
674 if (!priv->bitrate)
675 priv->bitrate = 1440000;
677 #endif
678 demuxer->accurate_seek = !priv->seek_by_bytes;
680 return demuxer;
683 static void check_internet_radio_hack(struct demuxer *demuxer)
685 struct lavf_priv *priv = demuxer->priv;
686 struct AVFormatContext *avfc = priv->avfc;
688 if (!matches_avinputformat_name(priv, "ogg"))
689 return;
690 if (priv->nb_streams_last == avfc->nb_streams)
691 return;
692 if (avfc->nb_streams - priv->nb_streams_last == 1
693 && priv->video_streams == 0 && priv->sub_streams == 0
694 && demuxer->a_streams[priv->audio_streams - 1]->format == 0x566f // vorbis
695 && (priv->audio_streams == 2 || priv->internet_radio_hack)
696 && demuxer->a_streams[0]->format == 0x566f) {
697 // extradata match could be checked but would require parsing
698 // headers, as the comment section will vary
699 if (!priv->internet_radio_hack) {
700 mp_msg(MSGT_DEMUX, MSGL_V,
701 "[lavf] enabling internet ogg radio hack\n");
703 priv->internet_radio_hack = true;
704 // use new per-track metadata as global metadata
705 AVDictionaryEntry *t = NULL;
706 AVStream *stream = avfc->streams[avfc->nb_streams - 1];
707 while ((t = av_dict_get(stream->metadata, "", t,
708 AV_DICT_IGNORE_SUFFIX)))
709 demux_info_add(demuxer, t->key, t->value);
710 } else {
711 if (priv->internet_radio_hack)
712 mp_tmsg(MSGT_DEMUX, MSGL_WARN, "[lavf] Internet radio ogg hack "
713 "was enabled, but stream characteristics changed.\n"
714 "This may or may not work.\n");
715 priv->internet_radio_hack = false;
719 static int destroy_avpacket(void *pkt)
721 av_free_packet(pkt);
722 return 0;
725 static int demux_lavf_fill_buffer(demuxer_t *demux, demux_stream_t *dsds)
727 lavf_priv_t *priv = demux->priv;
728 demux_packet_t *dp;
729 demux_stream_t *ds;
730 int id;
731 mp_msg(MSGT_DEMUX, MSGL_DBG2, "demux_lavf_fill_buffer()\n");
733 demux->filepos = stream_tell(demux->stream);
735 AVPacket *pkt = talloc(NULL, AVPacket);
736 if (av_read_frame(priv->avfc, pkt) < 0) {
737 talloc_free(pkt);
738 return 0;
740 talloc_set_destructor(pkt, destroy_avpacket);
742 // handle any new streams that might have been added
743 for (id = priv->nb_streams_last; id < priv->avfc->nb_streams; id++)
744 handle_stream(demux, priv->avfc, id);
745 check_internet_radio_hack(demux);
747 priv->nb_streams_last = priv->avfc->nb_streams;
749 id = pkt->stream_index;
751 if (id == demux->audio->id || priv->internet_radio_hack) {
752 // audio
753 ds = demux->audio;
754 if (!ds->sh) {
755 ds->sh = demux->a_streams[id];
756 mp_msg(MSGT_DEMUX, MSGL_V, "Auto-selected LAVF audio ID = %d\n",
757 ds->id);
759 } else if (id == demux->video->id) {
760 // video
761 ds = demux->video;
762 if (!ds->sh) {
763 ds->sh = demux->v_streams[id];
764 mp_msg(MSGT_DEMUX, MSGL_V, "Auto-selected LAVF video ID = %d\n",
765 ds->id);
767 } else if (id == demux->sub->id) {
768 // subtitle
769 ds = demux->sub;
770 sub_utf8 = 1;
771 } else {
772 talloc_free(pkt);
773 return 1;
776 // If the packet has pointers to temporary fields that could be
777 // overwritten/freed by next av_read_frame(), copy them to persistent
778 // allocations so we can safely queue the packet for any length of time.
779 if (av_dup_packet(pkt) < 0)
780 abort();
781 dp = new_demux_packet_fromdata(pkt->data, pkt->size);
782 dp->avpacket = pkt;
784 int64_t ts = priv->use_dts ? pkt->dts : pkt->pts;
785 if (ts != AV_NOPTS_VALUE) {
786 dp->pts = ts * av_q2d(priv->avfc->streams[id]->time_base);
787 priv->last_pts = dp->pts * AV_TIME_BASE;
788 // always set duration for subtitles, even if AV_PKT_FLAG_KEY isn't set,
789 // otherwise they will stay on screen to long if e.g. ASS is demuxed
790 // from mkv
791 if ((ds == demux->sub || (pkt->flags & AV_PKT_FLAG_KEY)) &&
792 pkt->convergence_duration > 0)
793 dp->duration = pkt->convergence_duration *
794 av_q2d(priv->avfc->streams[id]->time_base);
796 dp->pos = demux->filepos;
797 dp->flags = !!(pkt->flags & AV_PKT_FLAG_KEY);
798 // append packet to DS stream:
799 ds_add_packet(ds, dp);
800 return 1;
803 static void demux_seek_lavf(demuxer_t *demuxer, float rel_seek_secs,
804 float audio_delay, int flags)
806 lavf_priv_t *priv = demuxer->priv;
807 int avsflags = 0;
808 mp_msg(MSGT_DEMUX, MSGL_DBG2, "demux_seek_lavf(%p, %f, %f, %d)\n",
809 demuxer, rel_seek_secs, audio_delay, flags);
811 if (priv->seek_by_bytes) {
812 int64_t pos = demuxer->filepos;
813 rel_seek_secs *= priv->bitrate / 8;
814 pos += rel_seek_secs;
815 av_seek_frame(priv->avfc, -1, pos, AVSEEK_FLAG_BYTE);
816 return;
819 if (flags & SEEK_ABSOLUTE)
820 priv->last_pts = 0;
821 else if (rel_seek_secs < 0)
822 avsflags = AVSEEK_FLAG_BACKWARD;
823 if (flags & SEEK_FORWARD)
824 avsflags = 0;
825 else if (flags & SEEK_BACKWARD)
826 avsflags = AVSEEK_FLAG_BACKWARD;
827 if (flags & SEEK_FACTOR) {
828 if (priv->avfc->duration == 0 || priv->avfc->duration == AV_NOPTS_VALUE)
829 return;
830 priv->last_pts += rel_seek_secs * priv->avfc->duration;
831 } else
832 priv->last_pts += rel_seek_secs * AV_TIME_BASE;
833 if (av_seek_frame(priv->avfc, -1, priv->last_pts, avsflags) < 0) {
834 avsflags ^= AVSEEK_FLAG_BACKWARD;
835 av_seek_frame(priv->avfc, -1, priv->last_pts, avsflags);
839 static int demux_lavf_control(demuxer_t *demuxer, int cmd, void *arg)
841 lavf_priv_t *priv = demuxer->priv;
843 switch (cmd) {
844 case DEMUXER_CTRL_CORRECT_PTS:
845 return DEMUXER_CTRL_OK;
846 case DEMUXER_CTRL_GET_TIME_LENGTH:
847 if (priv->seek_by_bytes) {
848 /* Our bitrate estimate may be better than would be used in
849 * otherwise similar fallback code at higher level */
850 if (demuxer->movi_end <= 0)
851 return DEMUXER_CTRL_DONTKNOW;
852 *(double *)arg = (demuxer->movi_end - demuxer->movi_start) * 8 /
853 priv->bitrate;
854 return DEMUXER_CTRL_GUESS;
856 if (priv->avfc->duration == 0 || priv->avfc->duration == AV_NOPTS_VALUE)
857 return DEMUXER_CTRL_DONTKNOW;
859 *((double *)arg) = (double)priv->avfc->duration / AV_TIME_BASE;
860 return DEMUXER_CTRL_OK;
862 case DEMUXER_CTRL_GET_PERCENT_POS:
863 if (priv->seek_by_bytes)
864 return DEMUXER_CTRL_DONTKNOW; // let it use the fallback code
865 if (priv->avfc->duration == 0 || priv->avfc->duration == AV_NOPTS_VALUE)
866 return DEMUXER_CTRL_DONTKNOW;
868 *((int *)arg) = (int)((priv->last_pts - priv->avfc->start_time) * 100 /
869 priv->avfc->duration);
870 return DEMUXER_CTRL_OK;
871 case DEMUXER_CTRL_SWITCH_AUDIO:
872 case DEMUXER_CTRL_SWITCH_VIDEO:
874 int id = *((int *)arg);
875 int newid = -2;
876 int i, curridx = -1;
877 int nstreams, *pstreams;
878 demux_stream_t *ds;
880 if (cmd == DEMUXER_CTRL_SWITCH_VIDEO) {
881 ds = demuxer->video;
882 nstreams = priv->video_streams;
883 pstreams = priv->vstreams;
884 } else {
885 ds = demuxer->audio;
886 nstreams = priv->audio_streams;
887 pstreams = priv->astreams;
889 for (i = 0; i < nstreams; i++) {
890 if (pstreams[i] == ds->id) { //current stream id
891 curridx = i;
892 break;
896 if (id == -1) { // next track
897 i = (curridx + 2) % (nstreams + 1) - 1;
898 if (i >= 0)
899 newid = pstreams[i];
900 } else if (id >= 0 && id < nstreams) { // select track by id
901 i = id;
902 newid = pstreams[i];
903 } else // no sound
904 i = -1;
906 if (i == curridx) {
907 *(int *) arg = curridx < 0 ? -2 : curridx;
908 return DEMUXER_CTRL_OK;
909 } else {
910 ds_free_packs(ds);
911 if (ds->id >= 0)
912 priv->avfc->streams[ds->id]->discard = AVDISCARD_ALL;
913 ds->id = newid;
914 *(int *) arg = i < 0 ? -2 : i;
915 if (newid >= 0)
916 priv->avfc->streams[newid]->discard = AVDISCARD_NONE;
917 return DEMUXER_CTRL_OK;
920 case DEMUXER_CTRL_IDENTIFY_PROGRAM:
922 demux_program_t *prog = arg;
923 AVProgram *program;
924 int p, i;
925 int start;
927 prog->vid = prog->aid = prog->sid = -2;
928 if (priv->avfc->nb_programs < 1)
929 return DEMUXER_CTRL_DONTKNOW;
931 if (prog->progid == -1) {
932 p = 0;
933 while (p < priv->avfc->nb_programs && priv->avfc->programs[p]->id != priv->cur_program)
934 p++;
935 p = (p + 1) % priv->avfc->nb_programs;
936 } else {
937 for (i = 0; i < priv->avfc->nb_programs; i++)
938 if (priv->avfc->programs[i]->id == prog->progid)
939 break;
940 if (i == priv->avfc->nb_programs)
941 return DEMUXER_CTRL_DONTKNOW;
942 p = i;
944 start = p;
945 redo:
946 program = priv->avfc->programs[p];
947 for (i = 0; i < program->nb_stream_indexes; i++) {
948 switch (priv->avfc->streams[program->stream_index[i]]->codec->codec_type) {
949 case AVMEDIA_TYPE_VIDEO:
950 if (prog->vid == -2)
951 prog->vid = program->stream_index[i];
952 break;
953 case AVMEDIA_TYPE_AUDIO:
954 if (prog->aid == -2)
955 prog->aid = program->stream_index[i];
956 break;
957 case AVMEDIA_TYPE_SUBTITLE:
958 if (prog->sid == -2 && priv->avfc->streams[program->stream_index[i]]->codec->codec_id == CODEC_ID_TEXT)
959 prog->sid = program->stream_index[i];
960 break;
963 if (prog->aid >= 0 && prog->aid < MAX_A_STREAMS &&
964 demuxer->a_streams[prog->aid]) {
965 sh_audio_t *sh = demuxer->a_streams[prog->aid];
966 prog->aid = sh->aid;
967 } else
968 prog->aid = -2;
969 if (prog->vid >= 0 && prog->vid < MAX_V_STREAMS &&
970 demuxer->v_streams[prog->vid]) {
971 sh_video_t *sh = demuxer->v_streams[prog->vid];
972 prog->vid = sh->vid;
973 } else
974 prog->vid = -2;
975 if (prog->progid == -1 && prog->vid == -2 && prog->aid == -2) {
976 p = (p + 1) % priv->avfc->nb_programs;
977 if (p == start)
978 return DEMUXER_CTRL_DONTKNOW;
979 goto redo;
981 priv->cur_program = prog->progid = program->id;
982 return DEMUXER_CTRL_OK;
984 default:
985 return DEMUXER_CTRL_NOTIMPL;
989 static void demux_close_lavf(demuxer_t *demuxer)
991 lavf_priv_t *priv = demuxer->priv;
992 if (priv) {
993 if (priv->avfc) {
994 av_freep(&priv->avfc->key);
995 avformat_close_input(&priv->avfc);
997 av_freep(&priv->pb);
998 free(priv);
999 demuxer->priv = NULL;
1004 const demuxer_desc_t demuxer_desc_lavf = {
1005 "libavformat demuxer",
1006 "lavf",
1007 "libavformat",
1008 "Michael Niedermayer",
1009 "supports many formats, requires libavformat",
1010 DEMUXER_TYPE_LAVF,
1011 0, // Check after other demuxer
1012 lavf_check_file,
1013 demux_lavf_fill_buffer,
1014 demux_open_lavf,
1015 demux_close_lavf,
1016 demux_seek_lavf,
1017 demux_lavf_control
1020 const demuxer_desc_t demuxer_desc_lavf_preferred = {
1021 "libavformat preferred demuxer",
1022 "lavfpref",
1023 "libavformat",
1024 "Michael Niedermayer",
1025 "supports many formats, requires libavformat",
1026 DEMUXER_TYPE_LAVF_PREFERRED,
1028 lavf_check_preferred_file,
1029 demux_lavf_fill_buffer,
1030 demux_open_lavf,
1031 demux_close_lavf,
1032 demux_seek_lavf,
1033 demux_lavf_control