89eb759bc966aef1fea21557fd1680f1f60765ea
[libav.git] / libavformat / utils.c
1 /*
2 * various utility functions for use within Libav
3 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
4 *
5 * This file is part of Libav.
6 *
7 * Libav is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * Libav is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22 /* #define DEBUG */
23
24 #include "avformat.h"
25 #include "avio_internal.h"
26 #include "internal.h"
27 #include "libavcodec/internal.h"
28 #include "libavcodec/bytestream.h"
29 #include "libavutil/opt.h"
30 #include "libavutil/dict.h"
31 #include "libavutil/pixdesc.h"
32 #include "metadata.h"
33 #include "id3v2.h"
34 #include "libavutil/avassert.h"
35 #include "libavutil/avstring.h"
36 #include "libavutil/mathematics.h"
37 #include "libavutil/parseutils.h"
38 #include "libavutil/time.h"
39 #include "riff.h"
40 #include "audiointerleave.h"
41 #include "url.h"
42 #include <stdarg.h>
43 #if CONFIG_NETWORK
44 #include "network.h"
45 #endif
46
47 #undef NDEBUG
48 #include <assert.h>
49
50 /**
51 * @file
52 * various utility functions for use within Libav
53 */
54
55 unsigned avformat_version(void)
56 {
57 return LIBAVFORMAT_VERSION_INT;
58 }
59
60 const char *avformat_configuration(void)
61 {
62 return LIBAV_CONFIGURATION;
63 }
64
65 const char *avformat_license(void)
66 {
67 #define LICENSE_PREFIX "libavformat license: "
68 return LICENSE_PREFIX LIBAV_LICENSE + sizeof(LICENSE_PREFIX) - 1;
69 }
70
71 /** head of registered input format linked list */
72 static AVInputFormat *first_iformat = NULL;
73 /** head of registered output format linked list */
74 static AVOutputFormat *first_oformat = NULL;
75
76 AVInputFormat *av_iformat_next(AVInputFormat *f)
77 {
78 if(f) return f->next;
79 else return first_iformat;
80 }
81
82 AVOutputFormat *av_oformat_next(AVOutputFormat *f)
83 {
84 if(f) return f->next;
85 else return first_oformat;
86 }
87
88 void av_register_input_format(AVInputFormat *format)
89 {
90 AVInputFormat **p;
91 p = &first_iformat;
92 while (*p != NULL) p = &(*p)->next;
93 *p = format;
94 format->next = NULL;
95 }
96
97 void av_register_output_format(AVOutputFormat *format)
98 {
99 AVOutputFormat **p;
100 p = &first_oformat;
101 while (*p != NULL) p = &(*p)->next;
102 *p = format;
103 format->next = NULL;
104 }
105
106 int av_match_ext(const char *filename, const char *extensions)
107 {
108 const char *ext, *p;
109 char ext1[32], *q;
110
111 if(!filename)
112 return 0;
113
114 ext = strrchr(filename, '.');
115 if (ext) {
116 ext++;
117 p = extensions;
118 for(;;) {
119 q = ext1;
120 while (*p != '\0' && *p != ',' && q-ext1<sizeof(ext1)-1)
121 *q++ = *p++;
122 *q = '\0';
123 if (!av_strcasecmp(ext1, ext))
124 return 1;
125 if (*p == '\0')
126 break;
127 p++;
128 }
129 }
130 return 0;
131 }
132
133 static int match_format(const char *name, const char *names)
134 {
135 const char *p;
136 int len, namelen;
137
138 if (!name || !names)
139 return 0;
140
141 namelen = strlen(name);
142 while ((p = strchr(names, ','))) {
143 len = FFMAX(p - names, namelen);
144 if (!av_strncasecmp(name, names, len))
145 return 1;
146 names = p+1;
147 }
148 return !av_strcasecmp(name, names);
149 }
150
151 AVOutputFormat *av_guess_format(const char *short_name, const char *filename,
152 const char *mime_type)
153 {
154 AVOutputFormat *fmt = NULL, *fmt_found;
155 int score_max, score;
156
157 /* specific test for image sequences */
158 #if CONFIG_IMAGE2_MUXER
159 if (!short_name && filename &&
160 av_filename_number_test(filename) &&
161 ff_guess_image2_codec(filename) != AV_CODEC_ID_NONE) {
162 return av_guess_format("image2", NULL, NULL);
163 }
164 #endif
165 /* Find the proper file type. */
166 fmt_found = NULL;
167 score_max = 0;
168 while ((fmt = av_oformat_next(fmt))) {
169 score = 0;
170 if (fmt->name && short_name && !av_strcasecmp(fmt->name, short_name))
171 score += 100;
172 if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
173 score += 10;
174 if (filename && fmt->extensions &&
175 av_match_ext(filename, fmt->extensions)) {
176 score += 5;
177 }
178 if (score > score_max) {
179 score_max = score;
180 fmt_found = fmt;
181 }
182 }
183 return fmt_found;
184 }
185
186 enum AVCodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
187 const char *filename, const char *mime_type, enum AVMediaType type){
188 if(type == AVMEDIA_TYPE_VIDEO){
189 enum AVCodecID codec_id= AV_CODEC_ID_NONE;
190
191 #if CONFIG_IMAGE2_MUXER
192 if(!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")){
193 codec_id= ff_guess_image2_codec(filename);
194 }
195 #endif
196 if(codec_id == AV_CODEC_ID_NONE)
197 codec_id= fmt->video_codec;
198 return codec_id;
199 }else if(type == AVMEDIA_TYPE_AUDIO)
200 return fmt->audio_codec;
201 else if (type == AVMEDIA_TYPE_SUBTITLE)
202 return fmt->subtitle_codec;
203 else
204 return AV_CODEC_ID_NONE;
205 }
206
207 AVInputFormat *av_find_input_format(const char *short_name)
208 {
209 AVInputFormat *fmt = NULL;
210 while ((fmt = av_iformat_next(fmt))) {
211 if (match_format(short_name, fmt->name))
212 return fmt;
213 }
214 return NULL;
215 }
216
217 /* an arbitrarily chosen "sane" max packet size -- 50M */
218 #define SANE_CHUNK_SIZE (50000000)
219
220 /*
221 * Read the data in sane-sized chunks and append to pkt.
222 * Return the number of bytes read or an error.
223 */
224 static int append_packet_chunked(AVIOContext *s, AVPacket *pkt, int size)
225 {
226 int64_t chunk_size = size;
227 int orig_pos = pkt->pos; // av_grow_packet might reset pos
228 int orig_size = pkt->size;
229 int ret = 0;
230
231 do {
232 int prev_size = pkt->size;
233 int read_size;
234
235 /*
236 * When the caller requests a lot of data, limit it to the amount left
237 * in file or SANE_CHUNK_SIZE when it is not known
238 */
239 if (size > SANE_CHUNK_SIZE) {
240 int64_t filesize = avio_size(s) - avio_tell(s);
241 chunk_size = FFMAX(filesize, SANE_CHUNK_SIZE);
242 }
243 read_size = FFMIN(size, chunk_size);
244
245 ret = av_grow_packet(pkt, read_size);
246 if (ret < 0)
247 break;
248
249 ret = avio_read(s, pkt->data + prev_size, read_size);
250 if (ret != read_size) {
251 av_shrink_packet(pkt, prev_size + FFMAX(ret, 0));
252 break;
253 }
254
255 size -= read_size;
256 } while (size > 0);
257
258 pkt->pos = orig_pos;
259 if (!pkt->size)
260 av_free_packet(pkt);
261 return pkt->size > orig_size ? pkt->size - orig_size : ret;
262 }
263
264 int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
265 {
266 av_init_packet(pkt);
267 pkt->data = NULL;
268 pkt->size = 0;
269 pkt->pos = avio_tell(s);
270
271 return append_packet_chunked(s, pkt, size);
272 }
273
274 int av_append_packet(AVIOContext *s, AVPacket *pkt, int size)
275 {
276 if (!pkt->size)
277 return av_get_packet(s, pkt, size);
278 return append_packet_chunked(s, pkt, size);
279 }
280
281
282 int av_filename_number_test(const char *filename)
283 {
284 char buf[1024];
285 return filename && (av_get_frame_filename(buf, sizeof(buf), filename, 1)>=0);
286 }
287
288 AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
289 {
290 AVProbeData lpd = *pd;
291 AVInputFormat *fmt1 = NULL, *fmt;
292 int score, id3 = 0;
293
294 if (lpd.buf_size > 10 && ff_id3v2_match(lpd.buf, ID3v2_DEFAULT_MAGIC)) {
295 int id3len = ff_id3v2_tag_len(lpd.buf);
296 if (lpd.buf_size > id3len + 16) {
297 lpd.buf += id3len;
298 lpd.buf_size -= id3len;
299 }
300 id3 = 1;
301 }
302
303 fmt = NULL;
304 while ((fmt1 = av_iformat_next(fmt1))) {
305 if (!is_opened == !(fmt1->flags & AVFMT_NOFILE))
306 continue;
307 score = 0;
308 if (fmt1->read_probe) {
309 score = fmt1->read_probe(&lpd);
310 } else if (fmt1->extensions) {
311 if (av_match_ext(lpd.filename, fmt1->extensions)) {
312 score = 50;
313 }
314 }
315 if (score > *score_max) {
316 *score_max = score;
317 fmt = fmt1;
318 }else if (score == *score_max)
319 fmt = NULL;
320 }
321
322 /* a hack for files with huge id3v2 tags -- try to guess by file extension. */
323 if (!fmt && is_opened && *score_max < AVPROBE_SCORE_MAX/4) {
324 while ((fmt = av_iformat_next(fmt)))
325 if (fmt->extensions && av_match_ext(lpd.filename, fmt->extensions)) {
326 *score_max = AVPROBE_SCORE_MAX/4;
327 break;
328 }
329 }
330
331 if (!fmt && id3 && *score_max < AVPROBE_SCORE_MAX/4-1) {
332 while ((fmt = av_iformat_next(fmt)))
333 if (fmt->extensions && av_match_ext("mp3", fmt->extensions)) {
334 *score_max = AVPROBE_SCORE_MAX/4-1;
335 break;
336 }
337 }
338
339 return fmt;
340 }
341
342 AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened){
343 int score=0;
344 return av_probe_input_format2(pd, is_opened, &score);
345 }
346
347 static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st, AVProbeData *pd, int score)
348 {
349 static const struct {
350 const char *name; enum AVCodecID id; enum AVMediaType type;
351 } fmt_id_type[] = {
352 { "aac" , AV_CODEC_ID_AAC , AVMEDIA_TYPE_AUDIO },
353 { "ac3" , AV_CODEC_ID_AC3 , AVMEDIA_TYPE_AUDIO },
354 { "dts" , AV_CODEC_ID_DTS , AVMEDIA_TYPE_AUDIO },
355 { "eac3" , AV_CODEC_ID_EAC3 , AVMEDIA_TYPE_AUDIO },
356 { "h264" , AV_CODEC_ID_H264 , AVMEDIA_TYPE_VIDEO },
357 { "m4v" , AV_CODEC_ID_MPEG4 , AVMEDIA_TYPE_VIDEO },
358 { "mp3" , AV_CODEC_ID_MP3 , AVMEDIA_TYPE_AUDIO },
359 { "mpegvideo", AV_CODEC_ID_MPEG2VIDEO, AVMEDIA_TYPE_VIDEO },
360 { 0 }
361 };
362 AVInputFormat *fmt = av_probe_input_format2(pd, 1, &score);
363
364 if (fmt) {
365 int i;
366 av_log(s, AV_LOG_DEBUG, "Probe with size=%d, packets=%d detected %s with score=%d\n",
367 pd->buf_size, MAX_PROBE_PACKETS - st->probe_packets, fmt->name, score);
368 for (i = 0; fmt_id_type[i].name; i++) {
369 if (!strcmp(fmt->name, fmt_id_type[i].name)) {
370 st->codec->codec_id = fmt_id_type[i].id;
371 st->codec->codec_type = fmt_id_type[i].type;
372 break;
373 }
374 }
375 }
376 return !!fmt;
377 }
378
379 /************************************************************/
380 /* input media file */
381
382 /** size of probe buffer, for guessing file type from file contents */
383 #define PROBE_BUF_MIN 2048
384 #define PROBE_BUF_MAX (1<<20)
385
386 int av_probe_input_buffer(AVIOContext *pb, AVInputFormat **fmt,
387 const char *filename, void *logctx,
388 unsigned int offset, unsigned int max_probe_size)
389 {
390 AVProbeData pd = { filename ? filename : "", NULL, -offset };
391 unsigned char *buf = NULL;
392 int ret = 0, probe_size;
393
394 if (!max_probe_size) {
395 max_probe_size = PROBE_BUF_MAX;
396 } else if (max_probe_size > PROBE_BUF_MAX) {
397 max_probe_size = PROBE_BUF_MAX;
398 } else if (max_probe_size < PROBE_BUF_MIN) {
399 return AVERROR(EINVAL);
400 }
401
402 if (offset >= max_probe_size) {
403 return AVERROR(EINVAL);
404 }
405
406 for(probe_size= PROBE_BUF_MIN; probe_size<=max_probe_size && !*fmt;
407 probe_size = FFMIN(probe_size<<1, FFMAX(max_probe_size, probe_size+1))) {
408 int score = probe_size < max_probe_size ? AVPROBE_SCORE_MAX/4 : 0;
409 int buf_offset = (probe_size == PROBE_BUF_MIN) ? 0 : probe_size>>1;
410
411 if (probe_size < offset) {
412 continue;
413 }
414
415 /* read probe data */
416 buf = av_realloc(buf, probe_size + AVPROBE_PADDING_SIZE);
417 if ((ret = avio_read(pb, buf + buf_offset, probe_size - buf_offset)) < 0) {
418 /* fail if error was not end of file, otherwise, lower score */
419 if (ret != AVERROR_EOF) {
420 av_free(buf);
421 return ret;
422 }
423 score = 0;
424 ret = 0; /* error was end of file, nothing read */
425 }
426 pd.buf_size += ret;
427 pd.buf = &buf[offset];
428
429 memset(pd.buf + pd.buf_size, 0, AVPROBE_PADDING_SIZE);
430
431 /* guess file format */
432 *fmt = av_probe_input_format2(&pd, 1, &score);
433 if(*fmt){
434 if(score <= AVPROBE_SCORE_MAX/4){ //this can only be true in the last iteration
435 av_log(logctx, AV_LOG_WARNING, "Format detected only with low score of %d, misdetection possible!\n", score);
436 }else
437 av_log(logctx, AV_LOG_DEBUG, "Probed with size=%d and score=%d\n", probe_size, score);
438 }
439 }
440
441 if (!*fmt) {
442 av_free(buf);
443 return AVERROR_INVALIDDATA;
444 }
445
446 /* rewind. reuse probe buffer to avoid seeking */
447 if ((ret = ffio_rewind_with_probe_data(pb, buf, pd.buf_size)) < 0)
448 av_free(buf);
449
450 return ret;
451 }
452
453 /* open input file and probe the format if necessary */
454 static int init_input(AVFormatContext *s, const char *filename, AVDictionary **options)
455 {
456 int ret;
457 AVProbeData pd = {filename, NULL, 0};
458
459 if (s->pb) {
460 s->flags |= AVFMT_FLAG_CUSTOM_IO;
461 if (!s->iformat)
462 return av_probe_input_buffer(s->pb, &s->iformat, filename, s, 0, s->probesize);
463 else if (s->iformat->flags & AVFMT_NOFILE)
464 return AVERROR(EINVAL);
465 return 0;
466 }
467
468 if ( (s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
469 (!s->iformat && (s->iformat = av_probe_input_format(&pd, 0))))
470 return 0;
471
472 if ((ret = avio_open2(&s->pb, filename, AVIO_FLAG_READ,
473 &s->interrupt_callback, options)) < 0)
474 return ret;
475 if (s->iformat)
476 return 0;
477 return av_probe_input_buffer(s->pb, &s->iformat, filename, s, 0, s->probesize);
478 }
479
480 static AVPacket *add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt,
481 AVPacketList **plast_pktl){
482 AVPacketList *pktl = av_mallocz(sizeof(AVPacketList));
483 if (!pktl)
484 return NULL;
485
486 if (*packet_buffer)
487 (*plast_pktl)->next = pktl;
488 else
489 *packet_buffer = pktl;
490
491 /* add the packet in the buffered packet list */
492 *plast_pktl = pktl;
493 pktl->pkt= *pkt;
494 return &pktl->pkt;
495 }
496
497 static int queue_attached_pictures(AVFormatContext *s)
498 {
499 int i;
500 for (i = 0; i < s->nb_streams; i++)
501 if (s->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC &&
502 s->streams[i]->discard < AVDISCARD_ALL) {
503 AVPacket copy = s->streams[i]->attached_pic;
504 copy.buf = av_buffer_ref(copy.buf);
505 if (!copy.buf)
506 return AVERROR(ENOMEM);
507
508 add_to_pktbuf(&s->raw_packet_buffer, &copy, &s->raw_packet_buffer_end);
509 }
510 return 0;
511 }
512
513 int avformat_open_input(AVFormatContext **ps, const char *filename, AVInputFormat *fmt, AVDictionary **options)
514 {
515 AVFormatContext *s = *ps;
516 int ret = 0;
517 AVDictionary *tmp = NULL;
518 ID3v2ExtraMeta *id3v2_extra_meta = NULL;
519
520 if (!s && !(s = avformat_alloc_context()))
521 return AVERROR(ENOMEM);
522 if (fmt)
523 s->iformat = fmt;
524
525 if (options)
526 av_dict_copy(&tmp, *options, 0);
527
528 if ((ret = av_opt_set_dict(s, &tmp)) < 0)
529 goto fail;
530
531 if ((ret = init_input(s, filename, &tmp)) < 0)
532 goto fail;
533
534 /* check filename in case an image number is expected */
535 if (s->iformat->flags & AVFMT_NEEDNUMBER) {
536 if (!av_filename_number_test(filename)) {
537 ret = AVERROR(EINVAL);
538 goto fail;
539 }
540 }
541
542 s->duration = s->start_time = AV_NOPTS_VALUE;
543 av_strlcpy(s->filename, filename ? filename : "", sizeof(s->filename));
544
545 /* allocate private data */
546 if (s->iformat->priv_data_size > 0) {
547 if (!(s->priv_data = av_mallocz(s->iformat->priv_data_size))) {
548 ret = AVERROR(ENOMEM);
549 goto fail;
550 }
551 if (s->iformat->priv_class) {
552 *(const AVClass**)s->priv_data = s->iformat->priv_class;
553 av_opt_set_defaults(s->priv_data);
554 if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
555 goto fail;
556 }
557 }
558
559 /* e.g. AVFMT_NOFILE formats will not have a AVIOContext */
560 if (s->pb)
561 ff_id3v2_read(s, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta);
562
563 if (s->iformat->read_header)
564 if ((ret = s->iformat->read_header(s)) < 0)
565 goto fail;
566
567 if (id3v2_extra_meta &&
568 (ret = ff_id3v2_parse_apic(s, &id3v2_extra_meta)) < 0)
569 goto fail;
570 ff_id3v2_free_extra_meta(&id3v2_extra_meta);
571
572 if ((ret = queue_attached_pictures(s)) < 0)
573 goto fail;
574
575 if (s->pb && !s->data_offset)
576 s->data_offset = avio_tell(s->pb);
577
578 s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
579
580 if (options) {
581 av_dict_free(options);
582 *options = tmp;
583 }
584 *ps = s;
585 return 0;
586
587 fail:
588 ff_id3v2_free_extra_meta(&id3v2_extra_meta);
589 av_dict_free(&tmp);
590 if (s->pb && !(s->flags & AVFMT_FLAG_CUSTOM_IO))
591 avio_close(s->pb);
592 avformat_free_context(s);
593 *ps = NULL;
594 return ret;
595 }
596
597 /*******************************************************/
598
599 static void probe_codec(AVFormatContext *s, AVStream *st, const AVPacket *pkt)
600 {
601 if(st->codec->codec_id == AV_CODEC_ID_PROBE){
602 AVProbeData *pd = &st->probe_data;
603 av_log(s, AV_LOG_DEBUG, "probing stream %d\n", st->index);
604 --st->probe_packets;
605
606 if (pkt) {
607 pd->buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
608 memcpy(pd->buf+pd->buf_size, pkt->data, pkt->size);
609 pd->buf_size += pkt->size;
610 memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);
611 } else {
612 st->probe_packets = 0;
613 if (!pd->buf_size) {
614 av_log(s, AV_LOG_ERROR, "nothing to probe for stream %d\n",
615 st->index);
616 return;
617 }
618 }
619
620 if (!st->probe_packets ||
621 av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)) {
622 set_codec_from_probe_data(s, st, pd, st->probe_packets > 0 ? AVPROBE_SCORE_MAX/4 : 0);
623 if(st->codec->codec_id != AV_CODEC_ID_PROBE){
624 pd->buf_size=0;
625 av_freep(&pd->buf);
626 av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
627 }
628 }
629 }
630 }
631
632 int ff_read_packet(AVFormatContext *s, AVPacket *pkt)
633 {
634 int ret, i;
635 AVStream *st;
636
637 for(;;){
638 AVPacketList *pktl = s->raw_packet_buffer;
639
640 if (pktl) {
641 *pkt = pktl->pkt;
642 st = s->streams[pkt->stream_index];
643 if (st->codec->codec_id != AV_CODEC_ID_PROBE || !st->probe_packets ||
644 s->raw_packet_buffer_remaining_size < pkt->size) {
645 AVProbeData *pd;
646 if (st->probe_packets) {
647 probe_codec(s, st, NULL);
648 }
649 pd = &st->probe_data;
650 av_freep(&pd->buf);
651 pd->buf_size = 0;
652 s->raw_packet_buffer = pktl->next;
653 s->raw_packet_buffer_remaining_size += pkt->size;
654 av_free(pktl);
655 return 0;
656 }
657 }
658
659 pkt->data = NULL;
660 pkt->size = 0;
661 av_init_packet(pkt);
662 ret= s->iformat->read_packet(s, pkt);
663 if (ret < 0) {
664 if (!pktl || ret == AVERROR(EAGAIN))
665 return ret;
666 for (i = 0; i < s->nb_streams; i++) {
667 st = s->streams[i];
668 if (st->probe_packets) {
669 probe_codec(s, st, NULL);
670 }
671 }
672 continue;
673 }
674
675 if ((s->flags & AVFMT_FLAG_DISCARD_CORRUPT) &&
676 (pkt->flags & AV_PKT_FLAG_CORRUPT)) {
677 av_log(s, AV_LOG_WARNING,
678 "Dropped corrupted packet (stream = %d)\n",
679 pkt->stream_index);
680 av_free_packet(pkt);
681 continue;
682 }
683
684 st= s->streams[pkt->stream_index];
685
686 switch(st->codec->codec_type){
687 case AVMEDIA_TYPE_VIDEO:
688 if(s->video_codec_id) st->codec->codec_id= s->video_codec_id;
689 break;
690 case AVMEDIA_TYPE_AUDIO:
691 if(s->audio_codec_id) st->codec->codec_id= s->audio_codec_id;
692 break;
693 case AVMEDIA_TYPE_SUBTITLE:
694 if(s->subtitle_codec_id)st->codec->codec_id= s->subtitle_codec_id;
695 break;
696 }
697
698 if(!pktl && (st->codec->codec_id != AV_CODEC_ID_PROBE ||
699 !st->probe_packets))
700 return ret;
701
702 add_to_pktbuf(&s->raw_packet_buffer, pkt, &s->raw_packet_buffer_end);
703 s->raw_packet_buffer_remaining_size -= pkt->size;
704
705 probe_codec(s, st, pkt);
706 }
707 }
708
709 /**********************************************************/
710
711 /**
712 * Get the number of samples of an audio frame. Return -1 on error.
713 */
714 int ff_get_audio_frame_size(AVCodecContext *enc, int size, int mux)
715 {
716 int frame_size;
717
718 /* give frame_size priority if demuxing */
719 if (!mux && enc->frame_size > 1)
720 return enc->frame_size;
721
722 if ((frame_size = av_get_audio_frame_duration(enc, size)) > 0)
723 return frame_size;
724
725 /* fallback to using frame_size if muxing */
726 if (enc->frame_size > 1)
727 return enc->frame_size;
728
729 return -1;
730 }
731
732
733 /**
734 * Return the frame duration in seconds. Return 0 if not available.
735 */
736 void ff_compute_frame_duration(int *pnum, int *pden, AVStream *st,
737 AVCodecParserContext *pc, AVPacket *pkt)
738 {
739 int frame_size;
740
741 *pnum = 0;
742 *pden = 0;
743 switch(st->codec->codec_type) {
744 case AVMEDIA_TYPE_VIDEO:
745 if (st->avg_frame_rate.num) {
746 *pnum = st->avg_frame_rate.den;
747 *pden = st->avg_frame_rate.num;
748 } else if(st->time_base.num*1000LL > st->time_base.den) {
749 *pnum = st->time_base.num;
750 *pden = st->time_base.den;
751 }else if(st->codec->time_base.num*1000LL > st->codec->time_base.den){
752 *pnum = st->codec->time_base.num;
753 *pden = st->codec->time_base.den;
754 if (pc && pc->repeat_pict) {
755 if (*pnum > INT_MAX / (1 + pc->repeat_pict))
756 *pden /= 1 + pc->repeat_pict;
757 else
758 *pnum *= 1 + pc->repeat_pict;
759 }
760 //If this codec can be interlaced or progressive then we need a parser to compute duration of a packet
761 //Thus if we have no parser in such case leave duration undefined.
762 if(st->codec->ticks_per_frame>1 && !pc){
763 *pnum = *pden = 0;
764 }
765 }
766 break;
767 case AVMEDIA_TYPE_AUDIO:
768 frame_size = ff_get_audio_frame_size(st->codec, pkt->size, 0);
769 if (frame_size <= 0 || st->codec->sample_rate <= 0)
770 break;
771 *pnum = frame_size;
772 *pden = st->codec->sample_rate;
773 break;
774 default:
775 break;
776 }
777 }
778
779 static int is_intra_only(enum AVCodecID id)
780 {
781 const AVCodecDescriptor *d = avcodec_descriptor_get(id);
782 if (!d)
783 return 0;
784 if (d->type == AVMEDIA_TYPE_VIDEO && !(d->props & AV_CODEC_PROP_INTRA_ONLY))
785 return 0;
786 return 1;
787 }
788
789 static void update_initial_timestamps(AVFormatContext *s, int stream_index,
790 int64_t dts, int64_t pts)
791 {
792 AVStream *st= s->streams[stream_index];
793 AVPacketList *pktl= s->packet_buffer;
794
795 if(st->first_dts != AV_NOPTS_VALUE || dts == AV_NOPTS_VALUE || st->cur_dts == AV_NOPTS_VALUE)
796 return;
797
798 st->first_dts= dts - st->cur_dts;
799 st->cur_dts= dts;
800
801 for(; pktl; pktl= pktl->next){
802 if(pktl->pkt.stream_index != stream_index)
803 continue;
804 //FIXME think more about this check
805 if(pktl->pkt.pts != AV_NOPTS_VALUE && pktl->pkt.pts == pktl->pkt.dts)
806 pktl->pkt.pts += st->first_dts;
807
808 if(pktl->pkt.dts != AV_NOPTS_VALUE)
809 pktl->pkt.dts += st->first_dts;
810
811 if(st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
812 st->start_time= pktl->pkt.pts;
813 }
814 if (st->start_time == AV_NOPTS_VALUE)
815 st->start_time = pts;
816 }
817
818 static void update_initial_durations(AVFormatContext *s, AVStream *st,
819 int stream_index, int duration)
820 {
821 AVPacketList *pktl= s->packet_buffer;
822 int64_t cur_dts= 0;
823
824 if(st->first_dts != AV_NOPTS_VALUE){
825 cur_dts= st->first_dts;
826 for(; pktl; pktl= pktl->next){
827 if(pktl->pkt.stream_index == stream_index){
828 if(pktl->pkt.pts != pktl->pkt.dts || pktl->pkt.dts != AV_NOPTS_VALUE || pktl->pkt.duration)
829 break;
830 cur_dts -= duration;
831 }
832 }
833 pktl= s->packet_buffer;
834 st->first_dts = cur_dts;
835 }else if(st->cur_dts)
836 return;
837
838 for(; pktl; pktl= pktl->next){
839 if(pktl->pkt.stream_index != stream_index)
840 continue;
841 if(pktl->pkt.pts == pktl->pkt.dts && pktl->pkt.dts == AV_NOPTS_VALUE
842 && !pktl->pkt.duration){
843 pktl->pkt.dts= cur_dts;
844 if(!st->codec->has_b_frames)
845 pktl->pkt.pts= cur_dts;
846 cur_dts += duration;
847 if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
848 pktl->pkt.duration = duration;
849 }else
850 break;
851 }
852 if(st->first_dts == AV_NOPTS_VALUE)
853 st->cur_dts= cur_dts;
854 }
855
856 static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
857 AVCodecParserContext *pc, AVPacket *pkt)
858 {
859 int num, den, presentation_delayed, delay, i;
860 int64_t offset;
861
862 if (s->flags & AVFMT_FLAG_NOFILLIN)
863 return;
864
865 if((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)
866 pkt->dts= AV_NOPTS_VALUE;
867
868 /* do we have a video B-frame ? */
869 delay= st->codec->has_b_frames;
870 presentation_delayed = 0;
871
872 /* XXX: need has_b_frame, but cannot get it if the codec is
873 not initialized */
874 if (delay &&
875 pc && pc->pict_type != AV_PICTURE_TYPE_B)
876 presentation_delayed = 1;
877
878 if(pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && pkt->dts > pkt->pts && st->pts_wrap_bits<63
879 /*&& pkt->dts-(1LL<<st->pts_wrap_bits) < pkt->pts*/){
880 pkt->dts -= 1LL<<st->pts_wrap_bits;
881 }
882
883 // some mpeg2 in mpeg-ps lack dts (issue171 / input_file.mpg)
884 // we take the conservative approach and discard both
885 // Note, if this is misbehaving for a H.264 file then possibly presentation_delayed is not set correctly.
886 if(delay==1 && pkt->dts == pkt->pts && pkt->dts != AV_NOPTS_VALUE && presentation_delayed){
887 av_log(s, AV_LOG_DEBUG, "invalid dts/pts combination\n");
888 pkt->dts= pkt->pts= AV_NOPTS_VALUE;
889 }
890
891 if (pkt->duration == 0 && st->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
892 ff_compute_frame_duration(&num, &den, st, pc, pkt);
893 if (den && num) {
894 pkt->duration = av_rescale_rnd(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num, AV_ROUND_DOWN);
895
896 if(pkt->duration != 0 && s->packet_buffer)
897 update_initial_durations(s, st, pkt->stream_index, pkt->duration);
898 }
899 }
900
901 /* correct timestamps with byte offset if demuxers only have timestamps
902 on packet boundaries */
903 if(pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size){
904 /* this will estimate bitrate based on this frame's duration and size */
905 offset = av_rescale(pc->offset, pkt->duration, pkt->size);
906 if(pkt->pts != AV_NOPTS_VALUE)
907 pkt->pts += offset;
908 if(pkt->dts != AV_NOPTS_VALUE)
909 pkt->dts += offset;
910 }
911
912 if (pc && pc->dts_sync_point >= 0) {
913 // we have synchronization info from the parser
914 int64_t den = st->codec->time_base.den * (int64_t) st->time_base.num;
915 if (den > 0) {
916 int64_t num = st->codec->time_base.num * (int64_t) st->time_base.den;
917 if (pkt->dts != AV_NOPTS_VALUE) {
918 // got DTS from the stream, update reference timestamp
919 st->reference_dts = pkt->dts - pc->dts_ref_dts_delta * num / den;
920 pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
921 } else if (st->reference_dts != AV_NOPTS_VALUE) {
922 // compute DTS based on reference timestamp
923 pkt->dts = st->reference_dts + pc->dts_ref_dts_delta * num / den;
924 pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
925 }
926 if (pc->dts_sync_point > 0)
927 st->reference_dts = pkt->dts; // new reference
928 }
929 }
930
931 /* This may be redundant, but it should not hurt. */
932 if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
933 presentation_delayed = 1;
934
935 av_dlog(NULL,
936 "IN delayed:%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64" st:%d pc:%p\n",
937 presentation_delayed, pkt->pts, pkt->dts, st->cur_dts,
938 pkt->stream_index, pc);
939 /* interpolate PTS and DTS if they are not present */
940 //We skip H264 currently because delay and has_b_frames are not reliably set
941 if((delay==0 || (delay==1 && pc)) && st->codec->codec_id != AV_CODEC_ID_H264){
942 if (presentation_delayed) {
943 /* DTS = decompression timestamp */
944 /* PTS = presentation timestamp */
945 if (pkt->dts == AV_NOPTS_VALUE)
946 pkt->dts = st->last_IP_pts;
947 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts);
948 if (pkt->dts == AV_NOPTS_VALUE)
949 pkt->dts = st->cur_dts;
950
951 /* this is tricky: the dts must be incremented by the duration
952 of the frame we are displaying, i.e. the last I- or P-frame */
953 if (st->last_IP_duration == 0)
954 st->last_IP_duration = pkt->duration;
955 if(pkt->dts != AV_NOPTS_VALUE)
956 st->cur_dts = pkt->dts + st->last_IP_duration;
957 st->last_IP_duration = pkt->duration;
958 st->last_IP_pts= pkt->pts;
959 /* cannot compute PTS if not present (we can compute it only
960 by knowing the future */
961 } else if (pkt->pts != AV_NOPTS_VALUE ||
962 pkt->dts != AV_NOPTS_VALUE ||
963 pkt->duration ||
964 st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
965 int duration = pkt->duration;
966 if (!duration && st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
967 ff_compute_frame_duration(&num, &den, st, pc, pkt);
968 if (den && num) {
969 duration = av_rescale_rnd(1, num * (int64_t)st->time_base.den,
970 den * (int64_t)st->time_base.num,
971 AV_ROUND_DOWN);
972 if (duration != 0 && s->packet_buffer) {
973 update_initial_durations(s, st, pkt->stream_index,
974 duration);
975 }
976 }
977 }
978
979 if (pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE ||
980 duration) {
981 /* presentation is not delayed : PTS and DTS are the same */
982 if (pkt->pts == AV_NOPTS_VALUE)
983 pkt->pts = pkt->dts;
984 update_initial_timestamps(s, pkt->stream_index, pkt->pts,
985 pkt->pts);
986 if (pkt->pts == AV_NOPTS_VALUE)
987 pkt->pts = st->cur_dts;
988 pkt->dts = pkt->pts;
989 if (pkt->pts != AV_NOPTS_VALUE)
990 st->cur_dts = pkt->pts + duration;
991 }
992 }
993 }
994
995 if(pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
996 st->pts_buffer[0]= pkt->pts;
997 for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
998 FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
999 if(pkt->dts == AV_NOPTS_VALUE)
1000 pkt->dts= st->pts_buffer[0];
1001 if(st->codec->codec_id == AV_CODEC_ID_H264){ // we skipped it above so we try here
1002 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts); // this should happen on the first packet
1003 }
1004 if(pkt->dts > st->cur_dts)
1005 st->cur_dts = pkt->dts;
1006 }
1007
1008 av_dlog(NULL,
1009 "OUTdelayed:%d/%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64"\n",
1010 presentation_delayed, delay, pkt->pts, pkt->dts, st->cur_dts);
1011
1012 /* update flags */
1013 if (is_intra_only(st->codec->codec_id))
1014 pkt->flags |= AV_PKT_FLAG_KEY;
1015 if (pc)
1016 pkt->convergence_duration = pc->convergence_duration;
1017 }
1018
1019 static void free_packet_buffer(AVPacketList **pkt_buf, AVPacketList **pkt_buf_end)
1020 {
1021 while (*pkt_buf) {
1022 AVPacketList *pktl = *pkt_buf;
1023 *pkt_buf = pktl->next;
1024 av_free_packet(&pktl->pkt);
1025 av_freep(&pktl);
1026 }
1027 *pkt_buf_end = NULL;
1028 }
1029
1030 /**
1031 * Parse a packet, add all split parts to parse_queue
1032 *
1033 * @param pkt packet to parse, NULL when flushing the parser at end of stream
1034 */
1035 static int parse_packet(AVFormatContext *s, AVPacket *pkt, int stream_index)
1036 {
1037 AVPacket out_pkt = { 0 }, flush_pkt = { 0 };
1038 AVStream *st = s->streams[stream_index];
1039 uint8_t *data = pkt ? pkt->data : NULL;
1040 int size = pkt ? pkt->size : 0;
1041 int ret = 0, got_output = 0;
1042
1043 if (!pkt) {
1044 av_init_packet(&flush_pkt);
1045 pkt = &flush_pkt;
1046 got_output = 1;
1047 }
1048
1049 while (size > 0 || (pkt == &flush_pkt && got_output)) {
1050 int len;
1051
1052 av_init_packet(&out_pkt);
1053 len = av_parser_parse2(st->parser, st->codec,
1054 &out_pkt.data, &out_pkt.size, data, size,
1055 pkt->pts, pkt->dts, pkt->pos);
1056
1057 pkt->pts = pkt->dts = AV_NOPTS_VALUE;
1058 /* increment read pointer */
1059 data += len;
1060 size -= len;
1061
1062 got_output = !!out_pkt.size;
1063
1064 if (!out_pkt.size)
1065 continue;
1066
1067 /* set the duration */
1068 out_pkt.duration = 0;
1069 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
1070 if (st->codec->sample_rate > 0) {
1071 out_pkt.duration = av_rescale_q_rnd(st->parser->duration,
1072 (AVRational){ 1, st->codec->sample_rate },
1073 st->time_base,
1074 AV_ROUND_DOWN);
1075 }
1076 } else if (st->codec->time_base.num != 0 &&
1077 st->codec->time_base.den != 0) {
1078 out_pkt.duration = av_rescale_q_rnd(st->parser->duration,
1079 st->codec->time_base,
1080 st->time_base,
1081 AV_ROUND_DOWN);
1082 }
1083
1084 out_pkt.stream_index = st->index;
1085 out_pkt.pts = st->parser->pts;
1086 out_pkt.dts = st->parser->dts;
1087 out_pkt.pos = st->parser->pos;
1088
1089 if (st->parser->key_frame == 1 ||
1090 (st->parser->key_frame == -1 &&
1091 st->parser->pict_type == AV_PICTURE_TYPE_I))
1092 out_pkt.flags |= AV_PKT_FLAG_KEY;
1093
1094 compute_pkt_fields(s, st, st->parser, &out_pkt);
1095
1096 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
1097 out_pkt.flags & AV_PKT_FLAG_KEY) {
1098 ff_reduce_index(s, st->index);
1099 av_add_index_entry(st, st->parser->frame_offset, out_pkt.dts,
1100 0, 0, AVINDEX_KEYFRAME);
1101 }
1102
1103 if (out_pkt.data == pkt->data && out_pkt.size == pkt->size) {
1104 out_pkt.buf = pkt->buf;
1105 pkt->buf = NULL;
1106 #if FF_API_DESTRUCT_PACKET
1107 out_pkt.destruct = pkt->destruct;
1108 pkt->destruct = NULL;
1109 #endif
1110 }
1111 if ((ret = av_dup_packet(&out_pkt)) < 0)
1112 goto fail;
1113
1114 if (!add_to_pktbuf(&s->parse_queue, &out_pkt, &s->parse_queue_end)) {
1115 av_free_packet(&out_pkt);
1116 ret = AVERROR(ENOMEM);
1117 goto fail;
1118 }
1119 }
1120
1121
1122 /* end of the stream => close and free the parser */
1123 if (pkt == &flush_pkt) {
1124 av_parser_close(st->parser);
1125 st->parser = NULL;
1126 }
1127
1128 fail:
1129 av_free_packet(pkt);
1130 return ret;
1131 }
1132
1133 static int read_from_packet_buffer(AVPacketList **pkt_buffer,
1134 AVPacketList **pkt_buffer_end,
1135 AVPacket *pkt)
1136 {
1137 AVPacketList *pktl;
1138 av_assert0(*pkt_buffer);
1139 pktl = *pkt_buffer;
1140 *pkt = pktl->pkt;
1141 *pkt_buffer = pktl->next;
1142 if (!pktl->next)
1143 *pkt_buffer_end = NULL;
1144 av_freep(&pktl);
1145 return 0;
1146 }
1147
1148 static int read_frame_internal(AVFormatContext *s, AVPacket *pkt)
1149 {
1150 int ret = 0, i, got_packet = 0;
1151
1152 av_init_packet(pkt);
1153
1154 while (!got_packet && !s->parse_queue) {
1155 AVStream *st;
1156 AVPacket cur_pkt;
1157
1158 /* read next packet */
1159 ret = ff_read_packet(s, &cur_pkt);
1160 if (ret < 0) {
1161 if (ret == AVERROR(EAGAIN))
1162 return ret;
1163 /* flush the parsers */
1164 for(i = 0; i < s->nb_streams; i++) {
1165 st = s->streams[i];
1166 if (st->parser && st->need_parsing)
1167 parse_packet(s, NULL, st->index);
1168 }
1169 /* all remaining packets are now in parse_queue =>
1170 * really terminate parsing */
1171 break;
1172 }
1173 ret = 0;
1174 st = s->streams[cur_pkt.stream_index];
1175
1176 if (cur_pkt.pts != AV_NOPTS_VALUE &&
1177 cur_pkt.dts != AV_NOPTS_VALUE &&
1178 cur_pkt.pts < cur_pkt.dts) {
1179 av_log(s, AV_LOG_WARNING, "Invalid timestamps stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d\n",
1180 cur_pkt.stream_index,
1181 cur_pkt.pts,
1182 cur_pkt.dts,
1183 cur_pkt.size);
1184 }
1185 if (s->debug & FF_FDEBUG_TS)
1186 av_log(s, AV_LOG_DEBUG, "ff_read_packet stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
1187 cur_pkt.stream_index,
1188 cur_pkt.pts,
1189 cur_pkt.dts,
1190 cur_pkt.size,
1191 cur_pkt.duration,
1192 cur_pkt.flags);
1193
1194 if (st->need_parsing && !st->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) {
1195 st->parser = av_parser_init(st->codec->codec_id);
1196 if (!st->parser) {
1197 /* no parser available: just output the raw packets */
1198 st->need_parsing = AVSTREAM_PARSE_NONE;
1199 } else if(st->need_parsing == AVSTREAM_PARSE_HEADERS) {
1200 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1201 } else if(st->need_parsing == AVSTREAM_PARSE_FULL_ONCE) {
1202 st->parser->flags |= PARSER_FLAG_ONCE;
1203 }
1204 }
1205
1206 if (!st->need_parsing || !st->parser) {
1207 /* no parsing needed: we just output the packet as is */
1208 *pkt = cur_pkt;
1209 compute_pkt_fields(s, st, NULL, pkt);
1210 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
1211 (pkt->flags & AV_PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
1212 ff_reduce_index(s, st->index);
1213 av_add_index_entry(st, pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME);
1214 }
1215 got_packet = 1;
1216 } else if (st->discard < AVDISCARD_ALL) {
1217 if ((ret = parse_packet(s, &cur_pkt, cur_pkt.stream_index)) < 0)
1218 return ret;
1219 } else {
1220 /* free packet */
1221 av_free_packet(&cur_pkt);
1222 }
1223 }
1224
1225 if (!got_packet && s->parse_queue)
1226 ret = read_from_packet_buffer(&s->parse_queue, &s->parse_queue_end, pkt);
1227
1228 if(s->debug & FF_FDEBUG_TS)
1229 av_log(s, AV_LOG_DEBUG, "read_frame_internal stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
1230 pkt->stream_index,
1231 pkt->pts,
1232 pkt->dts,
1233 pkt->size,
1234 pkt->duration,
1235 pkt->flags);
1236
1237 return ret;
1238 }
1239
1240 int av_read_frame(AVFormatContext *s, AVPacket *pkt)
1241 {
1242 const int genpts = s->flags & AVFMT_FLAG_GENPTS;
1243 int eof = 0;
1244
1245 if (!genpts)
1246 return s->packet_buffer ? read_from_packet_buffer(&s->packet_buffer,
1247 &s->packet_buffer_end,
1248 pkt) :
1249 read_frame_internal(s, pkt);
1250
1251 for (;;) {
1252 int ret;
1253 AVPacketList *pktl = s->packet_buffer;
1254
1255 if (pktl) {
1256 AVPacket *next_pkt = &pktl->pkt;
1257
1258 if (next_pkt->dts != AV_NOPTS_VALUE) {
1259 int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;
1260 while (pktl && next_pkt->pts == AV_NOPTS_VALUE) {
1261 if (pktl->pkt.stream_index == next_pkt->stream_index &&
1262 (av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2LL << (wrap_bits - 1)) < 0) &&
1263 av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2LL << (wrap_bits - 1))) { //not b frame
1264 next_pkt->pts = pktl->pkt.dts;
1265 }
1266 pktl = pktl->next;
1267 }
1268 pktl = s->packet_buffer;
1269 }
1270
1271 /* read packet from packet buffer, if there is data */
1272 if (!(next_pkt->pts == AV_NOPTS_VALUE &&
1273 next_pkt->dts != AV_NOPTS_VALUE && !eof))
1274 return read_from_packet_buffer(&s->packet_buffer,
1275 &s->packet_buffer_end, pkt);
1276 }
1277
1278 ret = read_frame_internal(s, pkt);
1279 if (ret < 0) {
1280 if (pktl && ret != AVERROR(EAGAIN)) {
1281 eof = 1;
1282 continue;
1283 } else
1284 return ret;
1285 }
1286
1287 if (av_dup_packet(add_to_pktbuf(&s->packet_buffer, pkt,
1288 &s->packet_buffer_end)) < 0)
1289 return AVERROR(ENOMEM);
1290 }
1291 }
1292
1293 /* XXX: suppress the packet queue */
1294 static void flush_packet_queue(AVFormatContext *s)
1295 {
1296 free_packet_buffer(&s->parse_queue, &s->parse_queue_end);
1297 free_packet_buffer(&s->packet_buffer, &s->packet_buffer_end);
1298 free_packet_buffer(&s->raw_packet_buffer, &s->raw_packet_buffer_end);
1299
1300 s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
1301 }
1302
1303 /*******************************************************/
1304 /* seek support */
1305
1306 int av_find_default_stream_index(AVFormatContext *s)
1307 {
1308 int first_audio_index = -1;
1309 int i;
1310 AVStream *st;
1311
1312 if (s->nb_streams <= 0)
1313 return -1;
1314 for(i = 0; i < s->nb_streams; i++) {
1315 st = s->streams[i];
1316 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
1317 !(st->disposition & AV_DISPOSITION_ATTACHED_PIC)) {
1318 return i;
1319 }
1320 if (first_audio_index < 0 && st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1321 first_audio_index = i;
1322 }
1323 return first_audio_index >= 0 ? first_audio_index : 0;
1324 }
1325
1326 /**
1327 * Flush the frame reader.
1328 */
1329 void ff_read_frame_flush(AVFormatContext *s)
1330 {
1331 AVStream *st;
1332 int i, j;
1333
1334 flush_packet_queue(s);
1335
1336 /* for each stream, reset read state */
1337 for(i = 0; i < s->nb_streams; i++) {
1338 st = s->streams[i];
1339
1340 if (st->parser) {
1341 av_parser_close(st->parser);
1342 st->parser = NULL;
1343 }
1344 st->last_IP_pts = AV_NOPTS_VALUE;
1345 st->cur_dts = AV_NOPTS_VALUE; /* we set the current DTS to an unspecified origin */
1346 st->reference_dts = AV_NOPTS_VALUE;
1347
1348 st->probe_packets = MAX_PROBE_PACKETS;
1349
1350 for(j=0; j<MAX_REORDER_DELAY+1; j++)
1351 st->pts_buffer[j]= AV_NOPTS_VALUE;
1352 }
1353 }
1354
1355 void ff_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp)
1356 {
1357 int i;
1358
1359 for(i = 0; i < s->nb_streams; i++) {
1360 AVStream *st = s->streams[i];
1361
1362 st->cur_dts = av_rescale(timestamp,
1363 st->time_base.den * (int64_t)ref_st->time_base.num,
1364 st->time_base.num * (int64_t)ref_st->time_base.den);
1365 }
1366 }
1367
1368 void ff_reduce_index(AVFormatContext *s, int stream_index)
1369 {
1370 AVStream *st= s->streams[stream_index];
1371 unsigned int max_entries= s->max_index_size / sizeof(AVIndexEntry);
1372
1373 if((unsigned)st->nb_index_entries >= max_entries){
1374 int i;
1375 for(i=0; 2*i<st->nb_index_entries; i++)
1376 st->index_entries[i]= st->index_entries[2*i];
1377 st->nb_index_entries= i;
1378 }
1379 }
1380
1381 int ff_add_index_entry(AVIndexEntry **index_entries,
1382 int *nb_index_entries,
1383 unsigned int *index_entries_allocated_size,
1384 int64_t pos, int64_t timestamp, int size, int distance, int flags)
1385 {
1386 AVIndexEntry *entries, *ie;
1387 int index;
1388
1389 if((unsigned)*nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1390 return -1;
1391
1392 entries = av_fast_realloc(*index_entries,
1393 index_entries_allocated_size,
1394 (*nb_index_entries + 1) *
1395 sizeof(AVIndexEntry));
1396 if(!entries)
1397 return -1;
1398
1399 *index_entries= entries;
1400
1401 index= ff_index_search_timestamp(*index_entries, *nb_index_entries, timestamp, AVSEEK_FLAG_ANY);
1402
1403 if(index<0){
1404 index= (*nb_index_entries)++;
1405 ie= &entries[index];
1406 assert(index==0 || ie[-1].timestamp < timestamp);
1407 }else{
1408 ie= &entries[index];
1409 if(ie->timestamp != timestamp){
1410 if(ie->timestamp <= timestamp)
1411 return -1;
1412 memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(*nb_index_entries - index));
1413 (*nb_index_entries)++;
1414 }else if(ie->pos == pos && distance < ie->min_distance) //do not reduce the distance
1415 distance= ie->min_distance;
1416 }
1417
1418 ie->pos = pos;
1419 ie->timestamp = timestamp;
1420 ie->min_distance= distance;
1421 ie->size= size;
1422 ie->flags = flags;
1423
1424 return index;
1425 }
1426
1427 int av_add_index_entry(AVStream *st,
1428 int64_t pos, int64_t timestamp, int size, int distance, int flags)
1429 {
1430 return ff_add_index_entry(&st->index_entries, &st->nb_index_entries,
1431 &st->index_entries_allocated_size, pos,
1432 timestamp, size, distance, flags);
1433 }
1434
1435 int ff_index_search_timestamp(const AVIndexEntry *entries, int nb_entries,
1436 int64_t wanted_timestamp, int flags)
1437 {
1438 int a, b, m;
1439 int64_t timestamp;
1440
1441 a = - 1;
1442 b = nb_entries;
1443
1444 //optimize appending index entries at the end
1445 if(b && entries[b-1].timestamp < wanted_timestamp)
1446 a= b-1;
1447
1448 while (b - a > 1) {
1449 m = (a + b) >> 1;
1450 timestamp = entries[m].timestamp;
1451 if(timestamp >= wanted_timestamp)
1452 b = m;
1453 if(timestamp <= wanted_timestamp)
1454 a = m;
1455 }
1456 m= (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
1457
1458 if(!(flags & AVSEEK_FLAG_ANY)){
1459 while(m>=0 && m<nb_entries && !(entries[m].flags & AVINDEX_KEYFRAME)){
1460 m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
1461 }
1462 }
1463
1464 if(m == nb_entries)
1465 return -1;
1466 return m;
1467 }
1468
1469 int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
1470 int flags)
1471 {
1472 return ff_index_search_timestamp(st->index_entries, st->nb_index_entries,
1473 wanted_timestamp, flags);
1474 }
1475
1476 int ff_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
1477 {
1478 AVInputFormat *avif= s->iformat;
1479 int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
1480 int64_t ts_min, ts_max, ts;
1481 int index;
1482 int64_t ret;
1483 AVStream *st;
1484
1485 if (stream_index < 0)
1486 return -1;
1487
1488 av_dlog(s, "read_seek: %d %"PRId64"\n", stream_index, target_ts);
1489
1490 ts_max=
1491 ts_min= AV_NOPTS_VALUE;
1492 pos_limit= -1; //gcc falsely says it may be uninitialized
1493
1494 st= s->streams[stream_index];
1495 if(st->index_entries){
1496 AVIndexEntry *e;
1497
1498 index= av_index_search_timestamp(st, target_ts, flags | AVSEEK_FLAG_BACKWARD); //FIXME whole func must be checked for non-keyframe entries in index case, especially read_timestamp()
1499 index= FFMAX(index, 0);
1500 e= &st->index_entries[index];
1501
1502 if(e->timestamp <= target_ts || e->pos == e->min_distance){
1503 pos_min= e->pos;
1504 ts_min= e->timestamp;
1505 av_dlog(s, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",
1506 pos_min,ts_min);
1507 }else{
1508 assert(index==0);
1509 }
1510
1511 index= av_index_search_timestamp(st, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
1512 assert(index < st->nb_index_entries);
1513 if(index >= 0){
1514 e= &st->index_entries[index];
1515 assert(e->timestamp >= target_ts);
1516 pos_max= e->pos;
1517 ts_max= e->timestamp;
1518 pos_limit= pos_max - e->min_distance;
1519 av_dlog(s, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64" dts_max=%"PRId64"\n",
1520 pos_max,pos_limit, ts_max);
1521 }
1522 }
1523
1524 pos= ff_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit, ts_min, ts_max, flags, &ts, avif->read_timestamp);
1525 if(pos<0)
1526 return -1;
1527
1528 /* do the seek */
1529 if ((ret = avio_seek(s->pb, pos, SEEK_SET)) < 0)
1530 return ret;
1531
1532 ff_update_cur_dts(s, st, ts);
1533
1534 return 0;
1535 }
1536
1537 int64_t ff_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts,
1538 int64_t pos_min, int64_t pos_max, int64_t pos_limit,
1539 int64_t ts_min, int64_t ts_max, int flags, int64_t *ts_ret,
1540 int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ))
1541 {
1542 int64_t pos, ts;
1543 int64_t start_pos, filesize;
1544 int no_change;
1545
1546 av_dlog(s, "gen_seek: %d %"PRId64"\n", stream_index, target_ts);
1547
1548 if(ts_min == AV_NOPTS_VALUE){
1549 pos_min = s->data_offset;
1550 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1551 if (ts_min == AV_NOPTS_VALUE)
1552 return -1;
1553 }
1554
1555 if(ts_max == AV_NOPTS_VALUE){
1556 int step= 1024;
1557 filesize = avio_size(s->pb);
1558 pos_max = filesize - 1;
1559 do{
1560 pos_max -= step;
1561 ts_max = read_timestamp(s, stream_index, &pos_max, pos_max + step);
1562 step += step;
1563 }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
1564 if (ts_max == AV_NOPTS_VALUE)
1565 return -1;
1566
1567 for(;;){
1568 int64_t tmp_pos= pos_max + 1;
1569 int64_t tmp_ts= read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
1570 if(tmp_ts == AV_NOPTS_VALUE)
1571 break;
1572 ts_max= tmp_ts;
1573 pos_max= tmp_pos;
1574 if(tmp_pos >= filesize)
1575 break;
1576 }
1577 pos_limit= pos_max;
1578 }
1579
1580 if(ts_min > ts_max){
1581 return -1;
1582 }else if(ts_min == ts_max){
1583 pos_limit= pos_min;
1584 }
1585
1586 no_change=0;
1587 while (pos_min < pos_limit) {
1588 av_dlog(s, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64" dts_max=%"PRId64"\n",
1589 pos_min, pos_max, ts_min, ts_max);
1590 assert(pos_limit <= pos_max);
1591
1592 if(no_change==0){
1593 int64_t approximate_keyframe_distance= pos_max - pos_limit;
1594 // interpolate position (better than dichotomy)
1595 pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)
1596 + pos_min - approximate_keyframe_distance;
1597 }else if(no_change==1){
1598 // bisection, if interpolation failed to change min or max pos last time
1599 pos = (pos_min + pos_limit)>>1;
1600 }else{
1601 /* linear search if bisection failed, can only happen if there
1602 are very few or no keyframes between min/max */
1603 pos=pos_min;
1604 }
1605 if(pos <= pos_min)
1606 pos= pos_min + 1;
1607 else if(pos > pos_limit)
1608 pos= pos_limit;
1609 start_pos= pos;
1610
1611 ts = read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
1612 if(pos == pos_max)
1613 no_change++;
1614 else
1615 no_change=0;
1616 av_dlog(s, "%"PRId64" %"PRId64" %"PRId64" / %"PRId64" %"PRId64" %"PRId64" target:%"PRId64" limit:%"PRId64" start:%"PRId64" noc:%d\n",
1617 pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts,
1618 pos_limit, start_pos, no_change);
1619 if(ts == AV_NOPTS_VALUE){
1620 av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
1621 return -1;
1622 }
1623 assert(ts != AV_NOPTS_VALUE);
1624 if (target_ts <= ts) {
1625 pos_limit = start_pos - 1;
1626 pos_max = pos;
1627 ts_max = ts;
1628 }
1629 if (target_ts >= ts) {
1630 pos_min = pos;
1631 ts_min = ts;
1632 }
1633 }
1634
1635 pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
1636 ts = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min : ts_max;
1637 pos_min = pos;
1638 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1639 pos_min++;
1640 ts_max = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1641 av_dlog(s, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n",
1642 pos, ts_min, target_ts, ts_max);
1643 *ts_ret= ts;
1644 return pos;
1645 }
1646
1647 static int seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){
1648 int64_t pos_min, pos_max;
1649
1650 pos_min = s->data_offset;
1651 pos_max = avio_size(s->pb) - 1;
1652
1653 if (pos < pos_min) pos= pos_min;
1654 else if(pos > pos_max) pos= pos_max;
1655
1656 avio_seek(s->pb, pos, SEEK_SET);
1657
1658 return 0;
1659 }
1660
1661 static int seek_frame_generic(AVFormatContext *s,
1662 int stream_index, int64_t timestamp, int flags)
1663 {
1664 int index;
1665 int64_t ret;
1666 AVStream *st;
1667 AVIndexEntry *ie;
1668
1669 st = s->streams[stream_index];
1670
1671 index = av_index_search_timestamp(st, timestamp, flags);
1672
1673 if(index < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
1674 return -1;
1675
1676 if(index < 0 || index==st->nb_index_entries-1){
1677 AVPacket pkt;
1678
1679 if(st->nb_index_entries){
1680 assert(st->index_entries);
1681 ie= &st->index_entries[st->nb_index_entries-1];
1682 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
1683 return ret;
1684 ff_update_cur_dts(s, st, ie->timestamp);
1685 }else{
1686 if ((ret = avio_seek(s->pb, s->data_offset, SEEK_SET)) < 0)
1687 return ret;
1688 }
1689 for (;;) {
1690 int read_status;
1691 do{
1692 read_status = av_read_frame(s, &pkt);
1693 } while (read_status == AVERROR(EAGAIN));
1694 if (read_status < 0)
1695 break;
1696 av_free_packet(&pkt);
1697 if(stream_index == pkt.stream_index){
1698 if((pkt.flags & AV_PKT_FLAG_KEY) && pkt.dts > timestamp)
1699 break;
1700 }
1701 }
1702 index = av_index_search_timestamp(st, timestamp, flags);
1703 }
1704 if (index < 0)
1705 return -1;
1706
1707 ff_read_frame_flush(s);
1708 if (s->iformat->read_seek){
1709 if(s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
1710 return 0;
1711 }
1712 ie = &st->index_entries[index];
1713 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
1714 return ret;
1715 ff_update_cur_dts(s, st, ie->timestamp);
1716
1717 return 0;
1718 }
1719
1720 static int seek_frame_internal(AVFormatContext *s, int stream_index,
1721 int64_t timestamp, int flags)
1722 {
1723 int ret;
1724 AVStream *st;
1725
1726 if (flags & AVSEEK_FLAG_BYTE) {
1727 if (s->iformat->flags & AVFMT_NO_BYTE_SEEK)
1728 return -1;
1729 ff_read_frame_flush(s);
1730 return seek_frame_byte(s, stream_index, timestamp, flags);
1731 }
1732
1733 if(stream_index < 0){
1734 stream_index= av_find_default_stream_index(s);
1735 if(stream_index < 0)
1736 return -1;
1737
1738 st= s->streams[stream_index];
1739 /* timestamp for default must be expressed in AV_TIME_BASE units */
1740 timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1741 }
1742
1743 /* first, we try the format specific seek */
1744 if (s->iformat->read_seek) {
1745 ff_read_frame_flush(s);
1746 ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
1747 } else
1748 ret = -1;
1749 if (ret >= 0) {
1750 return 0;
1751 }
1752
1753 if (s->iformat->read_timestamp && !(s->iformat->flags & AVFMT_NOBINSEARCH)) {
1754 ff_read_frame_flush(s);
1755 return ff_seek_frame_binary(s, stream_index, timestamp, flags);
1756 } else if (!(s->iformat->flags & AVFMT_NOGENSEARCH)) {
1757 ff_read_frame_flush(s);
1758 return seek_frame_generic(s, stream_index, timestamp, flags);
1759 }
1760 else
1761 return -1;
1762 }
1763
1764 int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1765 {
1766 int ret = seek_frame_internal(s, stream_index, timestamp, flags);
1767
1768 if (ret >= 0)
1769 ret = queue_attached_pictures(s);
1770
1771 return ret;
1772 }
1773
1774 int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
1775 {
1776 if(min_ts > ts || max_ts < ts)
1777 return -1;
1778
1779 if (s->iformat->read_seek2) {
1780 int ret;
1781 ff_read_frame_flush(s);
1782 ret = s->iformat->read_seek2(s, stream_index, min_ts, ts, max_ts, flags);
1783
1784 if (ret >= 0)
1785 ret = queue_attached_pictures(s);
1786 return ret;
1787 }
1788
1789 if(s->iformat->read_timestamp){
1790 //try to seek via read_timestamp()
1791 }
1792
1793 //Fallback to old API if new is not implemented but old is
1794 //Note the old has somewat different sematics
1795 if(s->iformat->read_seek || 1)
1796 return av_seek_frame(s, stream_index, ts, flags | ((uint64_t)ts - min_ts > (uint64_t)max_ts - ts ? AVSEEK_FLAG_BACKWARD : 0));
1797
1798 // try some generic seek like seek_frame_generic() but with new ts semantics
1799 }
1800
1801 /*******************************************************/
1802
1803 /**
1804 * Return TRUE if the stream has accurate duration in any stream.
1805 *
1806 * @return TRUE if the stream has accurate duration for at least one component.
1807 */
1808 static int has_duration(AVFormatContext *ic)
1809 {
1810 int i;
1811 AVStream *st;
1812
1813 for(i = 0;i < ic->nb_streams; i++) {
1814 st = ic->streams[i];
1815 if (st->duration != AV_NOPTS_VALUE)
1816 return 1;
1817 }
1818 if (ic->duration != AV_NOPTS_VALUE)
1819 return 1;
1820 return 0;
1821 }
1822
1823 /**
1824 * Estimate the stream timings from the one of each components.
1825 *
1826 * Also computes the global bitrate if possible.
1827 */
1828 static void update_stream_timings(AVFormatContext *ic)
1829 {
1830 int64_t start_time, start_time1, end_time, end_time1;
1831 int64_t duration, duration1, filesize;
1832 int i;
1833 AVStream *st;
1834
1835 start_time = INT64_MAX;
1836 end_time = INT64_MIN;
1837 duration = INT64_MIN;
1838 for(i = 0;i < ic->nb_streams; i++) {
1839 st = ic->streams[i];
1840 if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
1841 start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
1842 start_time = FFMIN(start_time, start_time1);
1843 if (st->duration != AV_NOPTS_VALUE) {
1844 end_time1 = start_time1
1845 + av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1846 end_time = FFMAX(end_time, end_time1);
1847 }
1848 }
1849 if (st->duration != AV_NOPTS_VALUE) {
1850 duration1 = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1851 duration = FFMAX(duration, duration1);
1852 }
1853 }
1854 if (start_time != INT64_MAX) {
1855 ic->start_time = start_time;
1856 if (end_time != INT64_MIN)
1857 duration = FFMAX(duration, end_time - start_time);
1858 }
1859 if (duration != INT64_MIN) {
1860 ic->duration = duration;
1861 if (ic->pb && (filesize = avio_size(ic->pb)) > 0) {
1862 /* compute the bitrate */
1863 ic->bit_rate = (double)filesize * 8.0 * AV_TIME_BASE /
1864 (double)ic->duration;
1865 }
1866 }
1867 }
1868
1869 static void fill_all_stream_timings(AVFormatContext *ic)
1870 {
1871 int i;
1872 AVStream *st;
1873
1874 update_stream_timings(ic);
1875 for(i = 0;i < ic->nb_streams; i++) {
1876 st = ic->streams[i];
1877 if (st->start_time == AV_NOPTS_VALUE) {
1878 if(ic->start_time != AV_NOPTS_VALUE)
1879 st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q, st->time_base);
1880 if(ic->duration != AV_NOPTS_VALUE)
1881 st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q, st->time_base);
1882 }
1883 }
1884 }
1885
1886 static void estimate_timings_from_bit_rate(AVFormatContext *ic)
1887 {
1888 int64_t filesize, duration;
1889 int bit_rate, i;
1890 AVStream *st;
1891
1892 /* if bit_rate is already set, we believe it */
1893 if (ic->bit_rate <= 0) {
1894 bit_rate = 0;
1895 for(i=0;i<ic->nb_streams;i++) {
1896 st = ic->streams[i];
1897 if (st->codec->bit_rate > 0)
1898 bit_rate += st->codec->bit_rate;
1899 }
1900 ic->bit_rate = bit_rate;
1901 }
1902
1903 /* if duration is already set, we believe it */
1904 if (ic->duration == AV_NOPTS_VALUE &&
1905 ic->bit_rate != 0) {
1906 filesize = ic->pb ? avio_size(ic->pb) : 0;
1907 if (filesize > 0) {
1908 for(i = 0; i < ic->nb_streams; i++) {
1909 st = ic->streams[i];
1910 duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);
1911 if (st->duration == AV_NOPTS_VALUE)
1912 st->duration = duration;
1913 }
1914 }
1915 }
1916 }
1917
1918 #define DURATION_MAX_READ_SIZE 250000
1919 #define DURATION_MAX_RETRY 3
1920
1921 /* only usable for MPEG-PS streams */
1922 static void estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
1923 {
1924 AVPacket pkt1, *pkt = &pkt1;
1925 AVStream *st;
1926 int read_size, i, ret;
1927 int64_t end_time;
1928 int64_t filesize, offset, duration;
1929 int retry=0;
1930
1931 /* flush packet queue */
1932 flush_packet_queue(ic);
1933
1934 for (i=0; i<ic->nb_streams; i++) {
1935 st = ic->streams[i];
1936 if (st->start_time == AV_NOPTS_VALUE && st->first_dts == AV_NOPTS_VALUE)
1937 av_log(st->codec, AV_LOG_WARNING, "start time is not set in estimate_timings_from_pts\n");
1938
1939 if (st->parser) {
1940 av_parser_close(st->parser);
1941 st->parser= NULL;
1942 }
1943 }
1944
1945 /* estimate the end time (duration) */
1946 /* XXX: may need to support wrapping */
1947 filesize = ic->pb ? avio_size(ic->pb) : 0;
1948 end_time = AV_NOPTS_VALUE;
1949 do{
1950 offset = filesize - (DURATION_MAX_READ_SIZE<<retry);
1951 if (offset < 0)
1952 offset = 0;
1953
1954 avio_seek(ic->pb, offset, SEEK_SET);
1955 read_size = 0;
1956 for(;;) {
1957 if (read_size >= DURATION_MAX_READ_SIZE<<(FFMAX(retry-1,0)))
1958 break;
1959
1960 do {
1961 ret = ff_read_packet(ic, pkt);
1962 } while(ret == AVERROR(EAGAIN));
1963 if (ret != 0)
1964 break;
1965 read_size += pkt->size;
1966 st = ic->streams[pkt->stream_index];
1967 if (pkt->pts != AV_NOPTS_VALUE &&
1968 (st->start_time != AV_NOPTS_VALUE ||
1969 st->first_dts != AV_NOPTS_VALUE)) {
1970 duration = end_time = pkt->pts;
1971 if (st->start_time != AV_NOPTS_VALUE)
1972 duration -= st->start_time;
1973 else
1974 duration -= st->first_dts;
1975 if (duration < 0)
1976 duration += 1LL<<st->pts_wrap_bits;
1977 if (duration > 0) {
1978 if (st->duration == AV_NOPTS_VALUE || st->duration < duration)
1979 st->duration = duration;
1980 }
1981 }
1982 av_free_packet(pkt);
1983 }
1984 }while( end_time==AV_NOPTS_VALUE
1985 && filesize > (DURATION_MAX_READ_SIZE<<retry)
1986 && ++retry <= DURATION_MAX_RETRY);
1987
1988 fill_all_stream_timings(ic);
1989
1990 avio_seek(ic->pb, old_offset, SEEK_SET);
1991 for (i=0; i<ic->nb_streams; i++) {
1992 st= ic->streams[i];
1993 st->cur_dts= st->first_dts;
1994 st->last_IP_pts = AV_NOPTS_VALUE;
1995 st->reference_dts = AV_NOPTS_VALUE;
1996 }
1997 }
1998
1999 static void estimate_timings(AVFormatContext *ic, int64_t old_offset)
2000 {
2001 int64_t file_size;
2002
2003 /* get the file size, if possible */
2004 if (ic->iformat->flags & AVFMT_NOFILE) {
2005 file_size = 0;
2006 } else {
2007 file_size = avio_size(ic->pb);
2008 file_size = FFMAX(0, file_size);
2009 }
2010
2011 if ((!strcmp(ic->iformat->name, "mpeg") ||
2012 !strcmp(ic->iformat->name, "mpegts")) &&
2013 file_size && ic->pb->seekable) {
2014 /* get accurate estimate from the PTSes */
2015 estimate_timings_from_pts(ic, old_offset);
2016 } else if (has_duration(ic)) {
2017 /* at least one component has timings - we use them for all
2018 the components */
2019 fill_all_stream_timings(ic);
2020 } else {
2021 av_log(ic, AV_LOG_WARNING, "Estimating duration from bitrate, this may be inaccurate\n");
2022 /* less precise: use bitrate info */
2023 estimate_timings_from_bit_rate(ic);
2024 }
2025 update_stream_timings(ic);
2026
2027 {
2028 int i;
2029 AVStream av_unused *st;
2030 for(i = 0;i < ic->nb_streams; i++) {
2031 st = ic->streams[i];
2032 av_dlog(ic, "%d: start_time: %0.3f duration: %0.3f\n", i,
2033 (double) st->start_time / AV_TIME_BASE,
2034 (double) st->duration / AV_TIME_BASE);
2035 }
2036 av_dlog(ic, "stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
2037 (double) ic->start_time / AV_TIME_BASE,
2038 (double) ic->duration / AV_TIME_BASE,
2039 ic->bit_rate / 1000);
2040 }
2041 }
2042
2043 static int has_codec_parameters(AVStream *st)
2044 {
2045 AVCodecContext *avctx = st->codec;
2046 int val;
2047 switch (avctx->codec_type) {
2048 case AVMEDIA_TYPE_AUDIO:
2049 val = avctx->sample_rate && avctx->channels;
2050 if (st->info->found_decoder >= 0 && avctx->sample_fmt == AV_SAMPLE_FMT_NONE)
2051 return 0;
2052 break;
2053 case AVMEDIA_TYPE_VIDEO:
2054 val = avctx->width;
2055 if (st->info->found_decoder >= 0 && avctx->pix_fmt == AV_PIX_FMT_NONE)
2056 return 0;
2057 break;
2058 default:
2059 val = 1;
2060 break;
2061 }
2062 return avctx->codec_id != AV_CODEC_ID_NONE && val != 0;
2063 }
2064
2065 static int has_decode_delay_been_guessed(AVStream *st)
2066 {
2067 return st->codec->codec_id != AV_CODEC_ID_H264 ||
2068 st->info->nb_decoded_frames >= 6;
2069 }
2070
2071 /* returns 1 or 0 if or if not decoded data was returned, or a negative error */
2072 static int try_decode_frame(AVStream *st, AVPacket *avpkt, AVDictionary **options)
2073 {
2074 const AVCodec *codec;
2075 int got_picture = 1, ret = 0;
2076 AVFrame *frame = avcodec_alloc_frame();
2077 AVPacket pkt = *avpkt;
2078
2079 if (!frame)
2080 return AVERROR(ENOMEM);
2081
2082 if (!avcodec_is_open(st->codec) && !st->info->found_decoder) {
2083 AVDictionary *thread_opt = NULL;
2084
2085 codec = st->codec->codec ? st->codec->codec :
2086 avcodec_find_decoder(st->codec->codec_id);
2087
2088 if (!codec) {
2089 st->info->found_decoder = -1;
2090 ret = -1;
2091 goto fail;
2092 }
2093
2094 /* force thread count to 1 since the h264 decoder will not extract SPS
2095 * and PPS to extradata during multi-threaded decoding */
2096 av_dict_set(options ? options : &thread_opt, "threads", "1", 0);
2097 ret = avcodec_open2(st->codec, codec, options ? options : &thread_opt);
2098 if (!options)
2099 av_dict_free(&thread_opt);
2100 if (ret < 0) {
2101 st->info->found_decoder = -1;
2102 goto fail;
2103 }
2104 st->info->found_decoder = 1;
2105 } else if (!st->info->found_decoder)
2106 st->info->found_decoder = 1;
2107
2108 if (st->info->found_decoder < 0) {
2109 ret = -1;
2110 goto fail;
2111 }
2112
2113 while ((pkt.size > 0 || (!pkt.data && got_picture)) &&
2114 ret >= 0 &&
2115 (!has_codec_parameters(st) ||
2116 !has_decode_delay_been_guessed(st) ||
2117 (!st->codec_info_nb_frames && st->codec->codec->capabilities & CODEC_CAP_CHANNEL_CONF))) {
2118 got_picture = 0;
2119 avcodec_get_frame_defaults(frame);
2120 switch(st->codec->codec_type) {
2121 case AVMEDIA_TYPE_VIDEO:
2122 ret = avcodec_decode_video2(st->codec, frame,
2123 &got_picture, &pkt);
2124 break;
2125 case AVMEDIA_TYPE_AUDIO:
2126 ret = avcodec_decode_audio4(st->codec, frame, &got_picture, &pkt);
2127 break;
2128 default:
2129 break;
2130 }
2131 if (ret >= 0) {
2132 if (got_picture)
2133 st->info->nb_decoded_frames++;
2134 pkt.data += ret;
2135 pkt.size -= ret;
2136 ret = got_picture;
2137 }
2138 }
2139
2140 fail:
2141 avcodec_free_frame(&frame);
2142 return ret;
2143 }
2144
2145 unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum AVCodecID id)
2146 {
2147 while (tags->id != AV_CODEC_ID_NONE) {
2148 if (tags->id == id)
2149 return tags->tag;
2150 tags++;
2151 }
2152 return 0;
2153 }
2154
2155 enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
2156 {
2157 int i;
2158 for(i=0; tags[i].id != AV_CODEC_ID_NONE;i++) {
2159 if(tag == tags[i].tag)
2160 return tags[i].id;
2161 }
2162 for(i=0; tags[i].id != AV_CODEC_ID_NONE; i++) {
2163 if (avpriv_toupper4(tag) == avpriv_toupper4(tags[i].tag))
2164 return tags[i].id;
2165 }
2166 return AV_CODEC_ID_NONE;
2167 }
2168
2169 enum AVCodecID ff_get_pcm_codec_id(int bps, int flt, int be, int sflags)
2170 {
2171 if (flt) {
2172 switch (bps) {
2173 case 32: return be ? AV_CODEC_ID_PCM_F32BE : AV_CODEC_ID_PCM_F32LE;
2174 case 64: return be ? AV_CODEC_ID_PCM_F64BE : AV_CODEC_ID_PCM_F64LE;
2175 default: return AV_CODEC_ID_NONE;
2176 }
2177 } else {
2178 bps >>= 3;
2179 if (sflags & (1 << (bps - 1))) {
2180 switch (bps) {
2181 case 1: return AV_CODEC_ID_PCM_S8;
2182 case 2: return be ? AV_CODEC_ID_PCM_S16BE : AV_CODEC_ID_PCM_S16LE;
2183 case 3: return be ? AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
2184 case 4: return be ? AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
2185 default: return AV_CODEC_ID_NONE;
2186 }
2187 } else {
2188 switch (bps) {
2189 case 1: return AV_CODEC_ID_PCM_U8;
2190 case 2: return be ? AV_CODEC_ID_PCM_U16BE : AV_CODEC_ID_PCM_U16LE;
2191 case 3: return be ? AV_CODEC_ID_PCM_U24BE : AV_CODEC_ID_PCM_U24LE;
2192 case 4: return be ? AV_CODEC_ID_PCM_U32BE : AV_CODEC_ID_PCM_U32LE;
2193 default: return AV_CODEC_ID_NONE;
2194 }
2195 }
2196 }
2197 }
2198
2199 unsigned int av_codec_get_tag(const AVCodecTag * const *tags, enum AVCodecID id)
2200 {
2201 int i;
2202 for(i=0; tags && tags[i]; i++){
2203 int tag= ff_codec_get_tag(tags[i], id);
2204 if(tag) return tag;
2205 }
2206 return 0;
2207 }
2208
2209 enum AVCodecID av_codec_get_id(const AVCodecTag * const *tags, unsigned int tag)
2210 {
2211 int i;
2212 for(i=0; tags && tags[i]; i++){
2213 enum AVCodecID id= ff_codec_get_id(tags[i], tag);
2214 if(id!=AV_CODEC_ID_NONE) return id;
2215 }
2216 return AV_CODEC_ID_NONE;
2217 }
2218
2219 static void compute_chapters_end(AVFormatContext *s)
2220 {
2221 unsigned int i, j;
2222 int64_t max_time = s->duration + ((s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time);
2223
2224 for (i = 0; i < s->nb_chapters; i++)
2225 if (s->chapters[i]->end == AV_NOPTS_VALUE) {
2226 AVChapter *ch = s->chapters[i];
2227 int64_t end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q, ch->time_base)
2228 : INT64_MAX;
2229
2230 for (j = 0; j < s->nb_chapters; j++) {
2231 AVChapter *ch1 = s->chapters[j];
2232 int64_t next_start = av_rescale_q(ch1->start, ch1->time_base, ch->time_base);
2233 if (j != i && next_start > ch->start && next_start < end)
2234 end = next_start;
2235 }
2236 ch->end = (end == INT64_MAX) ? ch->start : end;
2237 }
2238 }
2239
2240 static int get_std_framerate(int i){
2241 if(i<60*12) return i*1001;
2242 else return ((const int[]){24,30,60,12,15})[i-60*12]*1000*12;
2243 }
2244
2245 /*
2246 * Is the time base unreliable.
2247 * This is a heuristic to balance between quick acceptance of the values in
2248 * the headers vs. some extra checks.
2249 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
2250 * MPEG-2 commonly misuses field repeat flags to store different framerates.
2251 * And there are "variable" fps files this needs to detect as well.
2252 */
2253 static int tb_unreliable(AVCodecContext *c){
2254 if( c->time_base.den >= 101L*c->time_base.num
2255 || c->time_base.den < 5L*c->time_base.num
2256 /* || c->codec_tag == AV_RL32("DIVX")
2257 || c->codec_tag == AV_RL32("XVID")*/
2258 || c->codec_id == AV_CODEC_ID_MPEG2VIDEO
2259 || c->codec_id == AV_CODEC_ID_H264
2260 )
2261 return 1;
2262 return 0;
2263 }
2264
2265 int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
2266 {
2267 int i, count, ret, read_size, j;
2268 AVStream *st;
2269 AVPacket pkt1, *pkt;
2270 int64_t old_offset = avio_tell(ic->pb);
2271 int orig_nb_streams = ic->nb_streams; // new streams might appear, no options for those
2272
2273 for(i=0;i<ic->nb_streams;i++) {
2274 const AVCodec *codec;
2275 AVDictionary *thread_opt = NULL;
2276 st = ic->streams[i];
2277
2278 //only for the split stuff
2279 if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE)) {
2280 st->parser = av_parser_init(st->codec->codec_id);
2281 if(st->need_parsing == AVSTREAM_PARSE_HEADERS && st->parser){
2282 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
2283 }
2284 }
2285 codec = st->codec->codec ? st->codec->codec :
2286 avcodec_find_decoder(st->codec->codec_id);
2287
2288 /* force thread count to 1 since the h264 decoder will not extract SPS
2289 * and PPS to extradata during multi-threaded decoding */
2290 av_dict_set(options ? &options[i] : &thread_opt, "threads", "1", 0);
2291
2292 /* Ensure that subtitle_header is properly set. */
2293 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
2294 && codec && !st->codec->codec)
2295 avcodec_open2(st->codec, codec, options ? &options[i]
2296 : &thread_opt);
2297
2298 //try to just open decoders, in case this is enough to get parameters
2299 if (!has_codec_parameters(st)) {
2300 if (codec && !st->codec->codec)
2301 avcodec_open2(st->codec, codec, options ? &options[i]
2302 : &thread_opt);
2303 }
2304 if (!options)
2305 av_dict_free(&thread_opt);
2306 }
2307
2308 for (i=0; i<ic->nb_streams; i++) {
2309 ic->streams[i]->info->fps_first_dts = AV_NOPTS_VALUE;
2310 ic->streams[i]->info->fps_last_dts = AV_NOPTS_VALUE;
2311 }
2312
2313 count = 0;
2314 read_size = 0;
2315 for(;;) {
2316 if (ff_check_interrupt(&ic->interrupt_callback)){
2317 ret= AVERROR_EXIT;
2318 av_log(ic, AV_LOG_DEBUG, "interrupted\n");
2319 break;
2320 }
2321
2322 /* check if one codec still needs to be handled */
2323 for(i=0;i<ic->nb_streams;i++) {
2324 int fps_analyze_framecount = 20;
2325
2326 st = ic->streams[i];
2327 if (!has_codec_parameters(st))
2328 break;
2329 /* if the timebase is coarse (like the usual millisecond precision
2330 of mkv), we need to analyze more frames to reliably arrive at
2331 the correct fps */
2332 if (av_q2d(st->time_base) > 0.0005)
2333 fps_analyze_framecount *= 2;
2334 if (ic->fps_probe_size >= 0)
2335 fps_analyze_framecount = ic->fps_probe_size;
2336 /* variable fps and no guess at the real fps */
2337 if( tb_unreliable(st->codec) && !st->avg_frame_rate.num
2338 && st->codec_info_nb_frames < fps_analyze_framecount
2339 && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2340 break;
2341 if(st->parser && st->parser->parser->split && !st->codec->extradata)
2342 break;
2343 if (st->first_dts == AV_NOPTS_VALUE &&
2344 (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2345 st->codec->codec_type == AVMEDIA_TYPE_AUDIO))
2346 break;
2347 }
2348 if (i == ic->nb_streams) {
2349 /* NOTE: if the format has no header, then we need to read
2350 some packets to get most of the streams, so we cannot
2351 stop here */
2352 if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
2353 /* if we found the info for all the codecs, we can stop */
2354 ret = count;
2355 av_log(ic, AV_LOG_DEBUG, "All info found\n");
2356 break;
2357 }
2358 }
2359 /* we did not get all the codec info, but we read too much data */
2360 if (read_size >= ic->probesize) {
2361 ret = count;
2362 av_log(ic, AV_LOG_DEBUG, "Probe buffer size limit %d reached\n", ic->probesize);
2363 break;
2364 }
2365
2366 /* NOTE: a new stream can be added there if no header in file
2367 (AVFMTCTX_NOHEADER) */
2368 ret = read_frame_internal(ic, &pkt1);
2369 if (ret == AVERROR(EAGAIN))
2370 continue;
2371
2372 if (ret < 0) {
2373 /* EOF or error*/
2374 AVPacket empty_pkt = { 0 };
2375 int err = 0;
2376 av_init_packet(&empty_pkt);
2377
2378 ret = -1; /* we could not have all the codec parameters before EOF */
2379 for(i=0;i<ic->nb_streams;i++) {
2380 st = ic->streams[i];
2381
2382 /* flush the decoders */
2383 if (st->info->found_decoder == 1) {
2384 do {
2385 err = try_decode_frame(st, &empty_pkt,
2386 (options && i < orig_nb_streams) ?
2387 &options[i] : NULL);
2388 } while (err > 0 && !has_codec_parameters(st));
2389 }
2390
2391 if (err < 0) {
2392 av_log(ic, AV_LOG_WARNING,
2393 "decoding for stream %d failed\n", st->index);
2394 } else if (!has_codec_parameters(st)) {
2395 char buf[256];
2396 avcodec_string(buf, sizeof(buf), st->codec, 0);
2397 av_log(ic, AV_LOG_WARNING,
2398 "Could not find codec parameters (%s)\n", buf);
2399 } else {
2400 ret = 0;
2401 }
2402 }
2403 break;
2404 }
2405
2406 if (ic->flags & AVFMT_FLAG_NOBUFFER) {
2407 pkt = &pkt1;
2408 } else {
2409 pkt = add_to_pktbuf(&ic->packet_buffer, &pkt1,
2410 &ic->packet_buffer_end);
2411 if ((ret = av_dup_packet(pkt)) < 0)
2412 goto find_stream_info_err;
2413 }
2414
2415 read_size += pkt->size;
2416
2417 st = ic->streams[pkt->stream_index];
2418 if (pkt->dts != AV_NOPTS_VALUE && st->codec_info_nb_frames > 1) {
2419 /* check for non-increasing dts */
2420 if (st->info->fps_last_dts != AV_NOPTS_VALUE &&
2421 st->info->fps_last_dts >= pkt->dts) {
2422 av_log(ic, AV_LOG_WARNING, "Non-increasing DTS in stream %d: "
2423 "packet %d with DTS %"PRId64", packet %d with DTS "
2424 "%"PRId64"\n", st->index, st->info->fps_last_dts_idx,
2425 st->info->fps_last_dts, st->codec_info_nb_frames, pkt->dts);
2426 st->info->fps_first_dts = st->info->fps_last_dts = AV_NOPTS_VALUE;
2427 }
2428 /* check for a discontinuity in dts - if the difference in dts
2429 * is more than 1000 times the average packet duration in the sequence,
2430 * we treat it as a discontinuity */
2431 if (st->info->fps_last_dts != AV_NOPTS_VALUE &&
2432 st->info->fps_last_dts_idx > st->info->fps_first_dts_idx &&
2433 (pkt->dts - st->info->fps_last_dts) / 1000 >
2434 (st->info->fps_last_dts - st->info->fps_first_dts) / (st->info->fps_last_dts_idx - st->info->fps_first_dts_idx)) {
2435 av_log(ic, AV_LOG_WARNING, "DTS discontinuity in stream %d: "
2436 "packet %d with DTS %"PRId64", packet %d with DTS "
2437 "%"PRId64"\n", st->index, st->info->fps_last_dts_idx,
2438 st->info->fps_last_dts, st->codec_info_nb_frames, pkt->dts);
2439 st->info->fps_first_dts = st->info->fps_last_dts = AV_NOPTS_VALUE;
2440 }
2441
2442 /* update stored dts values */
2443 if (st->info->fps_first_dts == AV_NOPTS_VALUE) {
2444 st->info->fps_first_dts = pkt->dts;
2445 st->info->fps_first_dts_idx = st->codec_info_nb_frames;
2446 }
2447 st->info->fps_last_dts = pkt->dts;
2448 st->info->fps_last_dts_idx = st->codec_info_nb_frames;
2449
2450 /* check max_analyze_duration */
2451 if (av_rescale_q(pkt->dts - st->info->fps_first_dts, st->time_base,
2452 AV_TIME_BASE_Q) >= ic->max_analyze_duration) {
2453 av_log(ic, AV_LOG_WARNING, "max_analyze_duration reached\n");
2454 break;
2455 }
2456 }
2457 if(st->parser && st->parser->parser->split && !st->codec->extradata){
2458 int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
2459 if (i > 0 && i < FF_MAX_EXTRADATA_SIZE) {
2460 st->codec->extradata_size= i;
2461 st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
2462 if (!st->codec->extradata)
2463 return AVERROR(ENOMEM);
2464 memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);
2465 memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2466 }
2467 }
2468
2469 /* if still no information, we try to open the codec and to
2470 decompress the frame. We try to avoid that in most cases as
2471 it takes longer and uses more memory. For MPEG-4, we need to
2472 decompress for QuickTime.
2473
2474 If CODEC_CAP_CHANNEL_CONF is set this will force decoding of at
2475 least one frame of codec data, this makes sure the codec initializes
2476 the channel configuration and does not only trust the values from the container.
2477 */
2478 try_decode_frame(st, pkt, (options && i < orig_nb_streams ) ? &options[i] : NULL);
2479
2480 st->codec_info_nb_frames++;
2481 count++;
2482 }
2483
2484 // close codecs which were opened in try_decode_frame()
2485 for(i=0;i<ic->nb_streams;i++) {
2486 st = ic->streams[i];
2487 avcodec_close(st->codec);
2488 }
2489 for(i=0;i<ic->nb_streams;i++) {
2490 st = ic->streams[i];
2491 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2492 /* estimate average framerate if not set by demuxer */
2493 if (!st->avg_frame_rate.num && st->info->fps_last_dts != st->info->fps_first_dts) {
2494 int64_t delta_dts = st->info->fps_last_dts - st->info->fps_first_dts;
2495 int delta_packets = st->info->fps_last_dts_idx - st->info->fps_first_dts_idx;
2496 int best_fps = 0;
2497 double best_error = 0.01;
2498
2499 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2500 delta_packets*(int64_t)st->time_base.den,
2501 delta_dts*(int64_t)st->time_base.num, 60000);
2502
2503 /* round guessed framerate to a "standard" framerate if it's
2504 * within 1% of the original estimate*/
2505 for (j = 1; j < MAX_STD_TIMEBASES; j++) {
2506 AVRational std_fps = { get_std_framerate(j), 12*1001 };
2507 double error = fabs(av_q2d(st->avg_frame_rate) / av_q2d(std_fps) - 1);
2508
2509 if (error < best_error) {
2510 best_error = error;
2511 best_fps = std_fps.num;
2512 }
2513 }
2514 if (best_fps) {
2515 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2516 best_fps, 12*1001, INT_MAX);
2517 }
2518 }
2519 }else if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2520 if(!st->codec->bits_per_coded_sample)
2521 st->codec->bits_per_coded_sample= av_get_bits_per_sample(st->codec->codec_id);
2522 // set stream disposition based on audio service type
2523 switch (st->codec->audio_service_type) {
2524 case AV_AUDIO_SERVICE_TYPE_EFFECTS:
2525 st->disposition = AV_DISPOSITION_CLEAN_EFFECTS; break;
2526 case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED:
2527 st->disposition = AV_DISPOSITION_VISUAL_IMPAIRED; break;
2528 case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED:
2529 st->disposition = AV_DISPOSITION_HEARING_IMPAIRED; break;
2530 case AV_AUDIO_SERVICE_TYPE_COMMENTARY:
2531 st->disposition = AV_DISPOSITION_COMMENT; break;
2532 case AV_AUDIO_SERVICE_TYPE_KARAOKE:
2533 st->disposition = AV_DISPOSITION_KARAOKE; break;
2534 }
2535 }
2536 }
2537
2538 estimate_timings(ic, old_offset);
2539
2540 compute_chapters_end(ic);
2541
2542 find_stream_info_err:
2543 for (i=0; i < ic->nb_streams; i++) {
2544 if (ic->streams[i]->codec)
2545 ic->streams[i]->codec->thread_count = 0;
2546 av_freep(&ic->streams[i]->info);
2547 }
2548 return ret;
2549 }
2550
2551 static AVProgram *find_program_from_stream(AVFormatContext *ic, int s)
2552 {
2553 int i, j;
2554
2555 for (i = 0; i < ic->nb_programs; i++)
2556 for (j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
2557 if (ic->programs[i]->stream_index[j] == s)
2558 return ic->programs[i];
2559 return NULL;
2560 }
2561
2562 int av_find_best_stream(AVFormatContext *ic,
2563 enum AVMediaType type,
2564 int wanted_stream_nb,
2565 int related_stream,
2566 AVCodec **decoder_ret,
2567 int flags)
2568 {
2569 int i, nb_streams = ic->nb_streams;
2570 int ret = AVERROR_STREAM_NOT_FOUND, best_count = -1;
2571 unsigned *program = NULL;
2572 AVCodec *decoder = NULL, *best_decoder = NULL;
2573
2574 if (related_stream >= 0 && wanted_stream_nb < 0) {
2575 AVProgram *p = find_program_from_stream(ic, related_stream);
2576 if (p) {
2577 program = p->stream_index;
2578 nb_streams = p->nb_stream_indexes;
2579 }
2580 }
2581 for (i = 0; i < nb_streams; i++) {
2582 int real_stream_index = program ? program[i] : i;
2583 AVStream *st = ic->streams[real_stream_index];
2584 AVCodecContext *avctx = st->codec;
2585 if (avctx->codec_type != type)
2586 continue;
2587 if (wanted_stream_nb >= 0 && real_stream_index != wanted_stream_nb)
2588 continue;
2589 if (st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED|AV_DISPOSITION_VISUAL_IMPAIRED))
2590 continue;
2591 if (decoder_ret) {
2592 decoder = avcodec_find_decoder(st->codec->codec_id);
2593 if (!decoder) {
2594 if (ret < 0)
2595 ret = AVERROR_DECODER_NOT_FOUND;
2596 continue;
2597 }
2598 }
2599 if (best_count >= st->codec_info_nb_frames)
2600 continue;
2601 best_count = st->codec_info_nb_frames;
2602 ret = real_stream_index;
2603 best_decoder = decoder;
2604 if (program && i == nb_streams - 1 && ret < 0) {
2605 program = NULL;
2606 nb_streams = ic->nb_streams;
2607 i = 0; /* no related stream found, try again with everything */
2608 }
2609 }
2610 if (decoder_ret)
2611 *decoder_ret = best_decoder;
2612 return ret;
2613 }
2614
2615 /*******************************************************/
2616
2617 int av_read_play(AVFormatContext *s)
2618 {
2619 if (s->iformat->read_play)
2620 return s->iformat->read_play(s);
2621 if (s->pb)
2622 return avio_pause(s->pb, 0);
2623 return AVERROR(ENOSYS);
2624 }
2625
2626 int av_read_pause(AVFormatContext *s)
2627 {
2628 if (s->iformat->read_pause)
2629 return s->iformat->read_pause(s);
2630 if (s->pb)
2631 return avio_pause(s->pb, 1);
2632 return AVERROR(ENOSYS);
2633 }
2634
2635 void avformat_free_context(AVFormatContext *s)
2636 {
2637 int i;
2638 AVStream *st;
2639
2640 av_opt_free(s);
2641 if (s->iformat && s->iformat->priv_class && s->priv_data)
2642 av_opt_free(s->priv_data);
2643
2644 for(i=0;i<s->nb_streams;i++) {
2645 /* free all data in a stream component */
2646 st = s->streams[i];
2647 if (st->parser) {
2648 av_parser_close(st->parser);
2649 }
2650 if (st->attached_pic.data)
2651 av_free_packet(&st->attached_pic);
2652 av_dict_free(&st->metadata);
2653 av_freep(&st->probe_data.buf);
2654 av_free(st->index_entries);
2655 av_free(st->codec->extradata);
2656 av_free(st->codec->subtitle_header);
2657 av_free(st->codec);
2658 av_free(st->priv_data);
2659 av_free(st->info);
2660 av_free(st);
2661 }
2662 for(i=s->nb_programs-1; i>=0; i--) {
2663 av_dict_free(&s->programs[i]->metadata);
2664 av_freep(&s->programs[i]->stream_index);
2665 av_freep(&s->programs[i]);
2666 }
2667 av_freep(&s->programs);
2668 av_freep(&s->priv_data);
2669 while(s->nb_chapters--) {
2670 av_dict_free(&s->chapters[s->nb_chapters]->metadata);
2671 av_free(s->chapters[s->nb_chapters]);
2672 }
2673 av_freep(&s->chapters);
2674 av_dict_free(&s->metadata);
2675 av_freep(&s->streams);
2676 av_free(s);
2677 }
2678
2679 void avformat_close_input(AVFormatContext **ps)
2680 {
2681 AVFormatContext *s = *ps;
2682 AVIOContext *pb = s->pb;
2683
2684 if ((s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
2685 (s->flags & AVFMT_FLAG_CUSTOM_IO))
2686 pb = NULL;
2687
2688 flush_packet_queue(s);
2689
2690 if (s->iformat) {
2691 if (s->iformat->read_close)
2692 s->iformat->read_close(s);
2693 }
2694
2695 avformat_free_context(s);
2696
2697 *ps = NULL;
2698
2699 avio_close(pb);
2700 }
2701
2702 AVStream *avformat_new_stream(AVFormatContext *s, AVCodec *c)
2703 {
2704 AVStream *st;
2705 int i;
2706 AVStream **streams;
2707
2708 if (s->nb_streams >= INT_MAX/sizeof(*streams))
2709 return NULL;
2710 streams = av_realloc(s->streams, (s->nb_streams + 1) * sizeof(*streams));
2711 if (!streams)
2712 return NULL;
2713 s->streams = streams;
2714
2715 st = av_mallocz(sizeof(AVStream));
2716 if (!st)
2717 return NULL;
2718 if (!(st->info = av_mallocz(sizeof(*st->info)))) {
2719 av_free(st);
2720 return NULL;
2721 }
2722
2723 st->codec = avcodec_alloc_context3(c);
2724 if (s->iformat) {
2725 /* no default bitrate if decoding */
2726 st->codec->bit_rate = 0;
2727 }
2728 st->index = s->nb_streams;
2729 st->start_time = AV_NOPTS_VALUE;
2730 st->duration = AV_NOPTS_VALUE;
2731 /* we set the current DTS to 0 so that formats without any timestamps
2732 but durations get some timestamps, formats with some unknown
2733 timestamps have their first few packets buffered and the
2734 timestamps corrected before they are returned to the user */
2735 st->cur_dts = 0;
2736 st->first_dts = AV_NOPTS_VALUE;
2737 st->probe_packets = MAX_PROBE_PACKETS;
2738
2739 /* default pts setting is MPEG-like */
2740 avpriv_set_pts_info(st, 33, 1, 90000);
2741 st->last_IP_pts = AV_NOPTS_VALUE;
2742 for(i=0; i<MAX_REORDER_DELAY+1; i++)
2743 st->pts_buffer[i]= AV_NOPTS_VALUE;
2744 st->reference_dts = AV_NOPTS_VALUE;
2745
2746 st->sample_aspect_ratio = (AVRational){0,1};
2747
2748 st->info->fps_first_dts = AV_NOPTS_VALUE;
2749 st->info->fps_last_dts = AV_NOPTS_VALUE;
2750
2751 s->streams[s->nb_streams++] = st;
2752 return st;
2753 }
2754
2755 AVProgram *av_new_program(AVFormatContext *ac, int id)
2756 {
2757 AVProgram *program=NULL;
2758 int i;
2759
2760 av_dlog(ac, "new_program: id=0x%04x\n", id);
2761
2762 for(i=0; i<ac->nb_programs; i++)
2763 if(ac->programs[i]->id == id)
2764 program = ac->programs[i];
2765
2766 if(!program){
2767 program = av_mallocz(sizeof(AVProgram));
2768 if (!program)
2769 return NULL;
2770 dynarray_add(&ac->programs, &ac->nb_programs, program);
2771 program->discard = AVDISCARD_NONE;
2772 }
2773 program->id = id;
2774
2775 return program;
2776 }
2777
2778 AVChapter *avpriv_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title)
2779 {
2780 AVChapter *chapter = NULL;
2781 int i;
2782
2783 for(i=0; i<s->nb_chapters; i++)
2784 if(s->chapters[i]->id == id)
2785 chapter = s->chapters[i];
2786
2787 if(!chapter){
2788 chapter= av_mallocz(sizeof(AVChapter));
2789 if(!chapter)
2790 return NULL;
2791 dynarray_add(&s->chapters, &s->nb_chapters, chapter);
2792 }
2793 av_dict_set(&chapter->metadata, "title", title, 0);
2794 chapter->id = id;
2795 chapter->time_base= time_base;
2796 chapter->start = start;
2797 chapter->end = end;
2798
2799 return chapter;
2800 }
2801
2802 void ff_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx)
2803 {
2804 int i, j;
2805 AVProgram *program=NULL;
2806 void *tmp;
2807
2808 if (idx >= ac->nb_streams) {
2809 av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
2810 return;
2811 }
2812
2813 for(i=0; i<ac->nb_programs; i++){
2814 if(ac->programs[i]->id != progid)
2815 continue;
2816 program = ac->programs[i];
2817 for(j=0; j<program->nb_stream_indexes; j++)
2818 if(program->stream_index[j] == idx)
2819 return;
2820
2821 tmp = av_realloc(program->stream_index, sizeof(unsigned int)*(program->nb_stream_indexes+1));
2822 if(!tmp)
2823 return;
2824 program->stream_index = tmp;
2825 program->stream_index[program->nb_stream_indexes++] = idx;
2826 return;
2827 }
2828 }
2829
2830 static void print_fps(double d, const char *postfix){
2831 uint64_t v= lrintf(d*100);
2832 if (v% 100 ) av_log(NULL, AV_LOG_INFO, ", %3.2f %s", d, postfix);
2833 else if(v%(100*1000)) av_log(NULL, AV_LOG_INFO, ", %1.0f %s", d, postfix);
2834 else av_log(NULL, AV_LOG_INFO, ", %1.0fk %s", d/1000, postfix);
2835 }
2836
2837 static void dump_metadata(void *ctx, AVDictionary *m, const char *indent)
2838 {
2839 if(m && !(av_dict_count(m) == 1 && av_dict_get(m, "language", NULL, 0))){
2840 AVDictionaryEntry *tag=NULL;
2841
2842 av_log(ctx, AV_LOG_INFO, "%sMetadata:\n", indent);
2843 while((tag=av_dict_get(m, "", tag, AV_DICT_IGNORE_SUFFIX))) {
2844 if(strcmp("language", tag->key))
2845 av_log(ctx, AV_LOG_INFO, "%s %-16s: %s\n", indent, tag->key, tag->value);
2846 }
2847 }
2848 }
2849
2850 /* "user interface" functions */
2851 static void dump_stream_format(AVFormatContext *ic, int i, int index, int is_output)
2852 {
2853 char buf[256];
2854 int flags = (is_output ? ic->oformat->flags : ic->iformat->flags);
2855 AVStream *st = ic->streams[i];
2856 int g = av_gcd(st->time_base.num, st->time_base.den);
2857 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL, 0);
2858 avcodec_string(buf, sizeof(buf), st->codec, is_output);
2859 av_log(NULL, AV_LOG_INFO, " Stream #%d.%d", index, i);
2860 /* the pid is an important information, so we display it */
2861 /* XXX: add a generic system */
2862 if (flags & AVFMT_SHOW_IDS)
2863 av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
2864 if (lang)
2865 av_log(NULL, AV_LOG_INFO, "(%s)", lang->value);
2866 av_log(NULL, AV_LOG_DEBUG, ", %d, %d/%d", st->codec_info_nb_frames, st->time_base.num/g, st->time_base.den/g);
2867 av_log(NULL, AV_LOG_INFO, ": %s", buf);
2868 if (st->sample_aspect_ratio.num && // default
2869 av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)) {
2870 AVRational display_aspect_ratio;
2871 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
2872 st->codec->width*st->sample_aspect_ratio.num,
2873 st->codec->height*st->sample_aspect_ratio.den,
2874 1024*1024);
2875 av_log(NULL, AV_LOG_INFO, ", PAR %d:%d DAR %d:%d",
2876 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
2877 display_aspect_ratio.num, display_aspect_ratio.den);
2878 }
2879 if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO){
2880 if(st->avg_frame_rate.den && st->avg_frame_rate.num)
2881 print_fps(av_q2d(st->avg_frame_rate), "fps");
2882 if(st->time_base.den && st->time_base.num)
2883 print_fps(1/av_q2d(st->time_base), "tbn");
2884 if(st->codec->time_base.den && st->codec->time_base.num)
2885 print_fps(1/av_q2d(st->codec->time_base), "tbc");
2886 }
2887 if (st->disposition & AV_DISPOSITION_DEFAULT)
2888 av_log(NULL, AV_LOG_INFO, " (default)");
2889 if (st->disposition & AV_DISPOSITION_DUB)
2890 av_log(NULL, AV_LOG_INFO, " (dub)");
2891 if (st->disposition & AV_DISPOSITION_ORIGINAL)
2892 av_log(NULL, AV_LOG_INFO, " (original)");
2893 if (st->disposition & AV_DISPOSITION_COMMENT)
2894 av_log(NULL, AV_LOG_INFO, " (comment)");
2895 if (st->disposition & AV_DISPOSITION_LYRICS)
2896 av_log(NULL, AV_LOG_INFO, " (lyrics)");
2897 if (st->disposition & AV_DISPOSITION_KARAOKE)
2898 av_log(NULL, AV_LOG_INFO, " (karaoke)");
2899 if (st->disposition & AV_DISPOSITION_FORCED)
2900 av_log(NULL, AV_LOG_INFO, " (forced)");
2901 if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
2902 av_log(NULL, AV_LOG_INFO, " (hearing impaired)");
2903 if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
2904 av_log(NULL, AV_LOG_INFO, " (visual impaired)");
2905 if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
2906 av_log(NULL, AV_LOG_INFO, " (clean effects)");
2907 av_log(NULL, AV_LOG_INFO, "\n");
2908 dump_metadata(NULL, st->metadata, " ");
2909 }
2910
2911 void av_dump_format(AVFormatContext *ic,
2912 int index,
2913 const char *url,
2914 int is_output)
2915 {
2916 int i;
2917 uint8_t *printed = ic->nb_streams ? av_mallocz(ic->nb_streams) : NULL;
2918 if (ic->nb_streams && !printed)
2919 return;
2920
2921 av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",
2922 is_output ? "Output" : "Input",
2923 index,
2924 is_output ? ic->oformat->name : ic->iformat->name,
2925 is_output ? "to" : "from", url);
2926 dump_metadata(NULL, ic->metadata, " ");
2927 if (!is_output) {
2928 av_log(NULL, AV_LOG_INFO, " Duration: ");
2929 if (ic->duration != AV_NOPTS_VALUE) {
2930 int hours, mins, secs, us;
2931 secs = ic->duration / AV_TIME_BASE;
2932 us = ic->duration % AV_TIME_BASE;
2933 mins = secs / 60;
2934 secs %= 60;
2935 hours = mins / 60;
2936 mins %= 60;
2937 av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%02d", hours, mins, secs,
2938 (100 * us) / AV_TIME_BASE);
2939 } else {
2940 av_log(NULL, AV_LOG_INFO, "N/A");
2941 }
2942 if (ic->start_time != AV_NOPTS_VALUE) {
2943 int secs, us;
2944 av_log(NULL, AV_LOG_INFO, ", start: ");
2945 secs = ic->start_time / AV_TIME_BASE;
2946 us = abs(ic->start_time % AV_TIME_BASE);
2947 av_log(NULL, AV_LOG_INFO, "%d.%06d",
2948 secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));
2949 }
2950 av_log(NULL, AV_LOG_INFO, ", bitrate: ");
2951 if (ic->bit_rate) {
2952 av_log(NULL, AV_LOG_INFO,"%d kb/s", ic->bit_rate / 1000);
2953 } else {
2954 av_log(NULL, AV_LOG_INFO, "N/A");
2955 }
2956 av_log(NULL, AV_LOG_INFO, "\n");
2957 }
2958 for (i = 0; i < ic->nb_chapters; i++) {
2959 AVChapter *ch = ic->chapters[i];
2960 av_log(NULL, AV_LOG_INFO, " Chapter #%d.%d: ", index, i);
2961 av_log(NULL, AV_LOG_INFO, "start %f, ", ch->start * av_q2d(ch->time_base));
2962 av_log(NULL, AV_LOG_INFO, "end %f\n", ch->end * av_q2d(ch->time_base));
2963
2964 dump_metadata(NULL, ch->metadata, " ");
2965 }
2966 if(ic->nb_programs) {
2967 int j, k, total = 0;
2968 for(j=0; j<ic->nb_programs; j++) {
2969 AVDictionaryEntry *name = av_dict_get(ic->programs[j]->metadata,
2970 "name", NULL, 0);
2971 av_log(NULL, AV_LOG_INFO, " Program %d %s\n", ic->programs[j]->id,
2972 name ? name->value : "");
2973 dump_metadata(NULL, ic->programs[j]->metadata, " ");
2974 for(k=0; k<ic->programs[j]->nb_stream_indexes; k++) {
2975 dump_stream_format(ic, ic->programs[j]->stream_index[k], index, is_output);
2976 printed[ic->programs[j]->stream_index[k]] = 1;
2977 }
2978 total += ic->programs[j]->nb_stream_indexes;
2979 }
2980 if (total < ic->nb_streams)
2981 av_log(NULL, AV_LOG_INFO, " No Program\n");
2982 }
2983 for(i=0;i<ic->nb_streams;i++)
2984 if (!printed[i])
2985 dump_stream_format(ic, i, index, is_output);
2986
2987 av_free(printed);
2988 }
2989
2990 uint64_t ff_ntp_time(void)
2991 {
2992 return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US;
2993 }
2994
2995 int av_get_frame_filename(char *buf, int buf_size,
2996 const char *path, int number)
2997 {
2998 const char *p;
2999 char *q, buf1[20], c;
3000 int nd, len, percentd_found;
3001
3002 q = buf;
3003 p = path;
3004 percentd_found = 0;
3005 for(;;) {
3006 c = *p++;
3007 if (c == '\0')
3008 break;
3009 if (c == '%') {
3010 do {
3011 nd = 0;
3012 while (av_isdigit(*p)) {
3013 nd = nd * 10 + *p++ - '0';
3014 }
3015 c = *p++;
3016 } while (av_isdigit(c));
3017
3018 switch(c) {
3019 case '%':
3020 goto addchar;
3021 case 'd':
3022 if (percentd_found)
3023 goto fail;
3024 percentd_found = 1;
3025 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
3026 len = strlen(buf1);
3027 if ((q - buf + len) > buf_size - 1)
3028 goto fail;
3029 memcpy(q, buf1, len);
3030 q += len;
3031 break;
3032 default:
3033 goto fail;
3034 }
3035 } else {
3036 addchar:
3037 if ((q - buf) < buf_size - 1)
3038 *q++ = c;
3039 }
3040 }
3041 if (!percentd_found)
3042 goto fail;
3043 *q = '\0';
3044 return 0;
3045 fail:
3046 *q = '\0';
3047 return -1;
3048 }
3049
3050 static void hex_dump_internal(void *avcl, FILE *f, int level,
3051 const uint8_t *buf, int size)
3052 {
3053 int len, i, j, c;
3054 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3055
3056 for(i=0;i<size;i+=16) {
3057 len = size - i;
3058 if (len > 16)
3059 len = 16;
3060 PRINT("%08x ", i);
3061 for(j=0;j<16;j++) {
3062 if (j < len)
3063 PRINT(" %02x", buf[i+j]);
3064 else
3065 PRINT(" ");
3066 }
3067 PRINT(" ");
3068 for(j=0;j<len;j++) {
3069 c = buf[i+j];
3070 if (c < ' ' || c > '~')
3071 c = '.';
3072 PRINT("%c", c);
3073 }
3074 PRINT("\n");
3075 }
3076 #undef PRINT
3077 }
3078
3079 void av_hex_dump(FILE *f, const uint8_t *buf, int size)
3080 {
3081 hex_dump_internal(NULL, f, 0, buf, size);
3082 }
3083
3084 void av_hex_dump_log(void *avcl, int level, const uint8_t *buf, int size)
3085 {
3086 hex_dump_internal(avcl, NULL, level, buf, size);
3087 }
3088
3089 static void pkt_dump_internal(void *avcl, FILE *f, int level, AVPacket *pkt, int dump_payload, AVRational time_base)
3090 {
3091 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3092 PRINT("stream #%d:\n", pkt->stream_index);
3093 PRINT(" keyframe=%d\n", ((pkt->flags & AV_PKT_FLAG_KEY) != 0));
3094 PRINT(" duration=%0.3f\n", pkt->duration * av_q2d(time_base));
3095 /* DTS is _always_ valid after av_read_frame() */
3096 PRINT(" dts=");
3097 if (pkt->dts == AV_NOPTS_VALUE)
3098 PRINT("N/A");
3099 else
3100 PRINT("%0.3f", pkt->dts * av_q2d(time_base));
3101 /* PTS may not be known if B-frames are present. */
3102 PRINT(" pts=");
3103 if (pkt->pts == AV_NOPTS_VALUE)
3104 PRINT("N/A");
3105 else
3106 PRINT("%0.3f", pkt->pts * av_q2d(time_base));
3107 PRINT("\n");
3108 PRINT(" size=%d\n", pkt->size);
3109 #undef PRINT
3110 if (dump_payload)
3111 av_hex_dump(f, pkt->data, pkt->size);
3112 }
3113
3114 void av_pkt_dump2(FILE *f, AVPacket *pkt, int dump_payload, AVStream *st)
3115 {
3116 pkt_dump_internal(NULL, f, 0, pkt, dump_payload, st->time_base);
3117 }
3118
3119 void av_pkt_dump_log2(void *avcl, int level, AVPacket *pkt, int dump_payload,
3120 AVStream *st)
3121 {
3122 pkt_dump_internal(avcl, NULL, level, pkt, dump_payload, st->time_base);
3123 }
3124
3125 void av_url_split(char *proto, int proto_size,
3126 char *authorization, int authorization_size,
3127 char *hostname, int hostname_size,
3128 int *port_ptr,
3129 char *path, int path_size,
3130 const char *url)
3131 {
3132 const char *p, *ls, *at, *col, *brk;
3133
3134 if (port_ptr) *port_ptr = -1;
3135 if (proto_size > 0) proto[0] = 0;
3136 if (authorization_size > 0) authorization[0] = 0;
3137 if (hostname_size > 0) hostname[0] = 0;
3138 if (path_size > 0) path[0] = 0;
3139
3140 /* parse protocol */
3141 if ((p = strchr(url, ':'))) {
3142 av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
3143 p++; /* skip ':' */
3144 if (*p == '/') p++;
3145 if (*p == '/') p++;
3146 } else {
3147 /* no protocol means plain filename */
3148 av_strlcpy(path, url, path_size);
3149 return;
3150 }
3151
3152 /* separate path from hostname */
3153 ls = strchr(p, '/');
3154 if(!ls)
3155 ls = strchr(p, '?');
3156 if(ls)
3157 av_strlcpy(path, ls, path_size);
3158 else
3159 ls = &p[strlen(p)]; // XXX
3160
3161 /* the rest is hostname, use that to parse auth/port */
3162 if (ls != p) {
3163 /* authorization (user[:pass]@hostname) */
3164 if ((at = strchr(p, '@')) && at < ls) {
3165 av_strlcpy(authorization, p,
3166 FFMIN(authorization_size, at + 1 - p));
3167 p = at + 1; /* skip '@' */
3168 }
3169
3170 if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
3171 /* [host]:port */
3172 av_strlcpy(hostname, p + 1,
3173 FFMIN(hostname_size, brk - p));
3174 if (brk[1] == ':' && port_ptr)
3175 *port_ptr = atoi(brk + 2);
3176 } else if ((col = strchr(p, ':')) && col < ls) {
3177 av_strlcpy(hostname, p,
3178 FFMIN(col + 1 - p, hostname_size));
3179 if (port_ptr) *port_ptr = atoi(col + 1);
3180 } else
3181 av_strlcpy(hostname, p,
3182 FFMIN(ls + 1 - p, hostname_size));
3183 }
3184 }
3185
3186 char *ff_data_to_hex(char *buff, const uint8_t *src, int s, int lowercase)
3187 {
3188 int i;
3189 static const char hex_table_uc[16] = { '0', '1', '2', '3',
3190 '4', '5', '6', '7',
3191 '8', '9', 'A', 'B',
3192 'C', 'D', 'E', 'F' };
3193 static const char hex_table_lc[16] = { '0', '1', '2', '3',
3194 '4', '5', '6', '7',
3195 '8', '9', 'a', 'b',
3196 'c', 'd', 'e', 'f' };
3197 const char *hex_table = lowercase ? hex_table_lc : hex_table_uc;
3198
3199 for(i = 0; i < s; i++) {
3200 buff[i * 2] = hex_table[src[i] >> 4];
3201 buff[i * 2 + 1] = hex_table[src[i] & 0xF];
3202 }
3203
3204 return buff;
3205 }
3206
3207 int ff_hex_to_data(uint8_t *data, const char *p)
3208 {
3209 int c, len, v;
3210
3211 len = 0;
3212 v = 1;
3213 for (;;) {
3214 p += strspn(p, SPACE_CHARS);
3215 if (*p == '\0')
3216 break;
3217 c = av_toupper((unsigned char) *p++);
3218 if (c >= '0' && c <= '9')
3219 c = c - '0';
3220 else if (c >= 'A' && c <= 'F')
3221 c = c - 'A' + 10;
3222 else
3223 break;
3224 v = (v << 4) | c;
3225 if (v & 0x100) {
3226 if (data)
3227 data[len] = v;
3228 len++;
3229 v = 1;
3230 }
3231 }
3232 return len;
3233 }
3234
3235 void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits,
3236 unsigned int pts_num, unsigned int pts_den)
3237 {
3238 AVRational new_tb;
3239 if(av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)){
3240 if(new_tb.num != pts_num)
3241 av_log(NULL, AV_LOG_DEBUG, "st:%d removing common factor %d from timebase\n", s->index, pts_num/new_tb.num);
3242 }else
3243 av_log(NULL, AV_LOG_WARNING, "st:%d has too large timebase, reducing\n", s->index);
3244
3245 if(new_tb.num <= 0 || new_tb.den <= 0) {
3246 av_log(NULL, AV_LOG_ERROR, "Ignoring attempt to set invalid timebase for st:%d\n", s->index);
3247 return;
3248 }
3249 s->time_base = new_tb;
3250 s->pts_wrap_bits = pts_wrap_bits;
3251 }
3252
3253 int ff_url_join(char *str, int size, const char *proto,
3254 const char *authorization, const char *hostname,
3255 int port, const char *fmt, ...)
3256 {
3257 #if CONFIG_NETWORK
3258 struct addrinfo hints = { 0 }, *ai;
3259 #endif
3260
3261 str[0] = '\0';
3262 if (proto)
3263 av_strlcatf(str, size, "%s://", proto);
3264 if (authorization && authorization[0])
3265 av_strlcatf(str, size, "%s@", authorization);
3266 #if CONFIG_NETWORK && defined(AF_INET6)
3267 /* Determine if hostname is a numerical IPv6 address,
3268 * properly escape it within [] in that case. */
3269 hints.ai_flags = AI_NUMERICHOST;
3270 if (!getaddrinfo(hostname, NULL, &hints, &ai)) {
3271 if (ai->ai_family == AF_INET6) {
3272 av_strlcat(str, "[", size);
3273 av_strlcat(str, hostname, size);
3274 av_strlcat(str, "]", size);
3275 } else {
3276 av_strlcat(str, hostname, size);
3277 }
3278 freeaddrinfo(ai);
3279 } else
3280 #endif
3281 /* Not an IPv6 address, just output the plain string. */
3282 av_strlcat(str, hostname, size);
3283
3284 if (port >= 0)
3285 av_strlcatf(str, size, ":%d", port);
3286 if (fmt) {
3287 va_list vl;
3288 int len = strlen(str);
3289
3290 va_start(vl, fmt);
3291 vsnprintf(str + len, size > len ? size - len : 0, fmt, vl);
3292 va_end(vl);
3293 }
3294 return strlen(str);
3295 }
3296
3297 int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
3298 AVFormatContext *src)
3299 {
3300 AVPacket local_pkt;
3301
3302 local_pkt = *pkt;
3303 local_pkt.stream_index = dst_stream;
3304 if (pkt->pts != AV_NOPTS_VALUE)
3305 local_pkt.pts = av_rescale_q(pkt->pts,
3306 src->streams[pkt->stream_index]->time_base,
3307 dst->streams[dst_stream]->time_base);
3308 if (pkt->dts != AV_NOPTS_VALUE)
3309 local_pkt.dts = av_rescale_q(pkt->dts,
3310 src->streams[pkt->stream_index]->time_base,
3311 dst->streams[dst_stream]->time_base);
3312 return av_write_frame(dst, &local_pkt);
3313 }
3314
3315 void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf,
3316 void *context)
3317 {
3318 const char *ptr = str;
3319
3320 /* Parse key=value pairs. */
3321 for (;;) {
3322 const char *key;
3323 char *dest = NULL, *dest_end;
3324 int key_len, dest_len = 0;
3325
3326 /* Skip whitespace and potential commas. */
3327 while (*ptr && (av_isspace(*ptr) || *ptr == ','))
3328 ptr++;
3329 if (!*ptr)
3330 break;
3331
3332 key = ptr;
3333
3334 if (!(ptr = strchr(key, '=')))
3335 break;
3336 ptr++;
3337 key_len = ptr - key;
3338
3339 callback_get_buf(context, key, key_len, &dest, &dest_len);
3340 dest_end = dest + dest_len - 1;
3341
3342 if (*ptr == '\"') {
3343 ptr++;
3344 while (*ptr && *ptr != '\"') {
3345 if (*ptr == '\\') {
3346 if (!ptr[1])
3347 break;
3348 if (dest && dest < dest_end)
3349 *dest++ = ptr[1];
3350 ptr += 2;
3351 } else {
3352 if (dest && dest < dest_end)
3353 *dest++ = *ptr;
3354 ptr++;
3355 }
3356 }
3357 if (*ptr == '\"')
3358 ptr++;
3359 } else {
3360 for (; *ptr && !(av_isspace(*ptr) || *ptr == ','); ptr++)
3361 if (dest && dest < dest_end)
3362 *dest++ = *ptr;
3363 }
3364 if (dest)
3365 *dest = 0;
3366 }
3367 }
3368
3369 int ff_find_stream_index(AVFormatContext *s, int id)
3370 {
3371 int i;
3372 for (i = 0; i < s->nb_streams; i++) {
3373 if (s->streams[i]->id == id)
3374 return i;
3375 }
3376 return -1;
3377 }
3378
3379 void ff_make_absolute_url(char *buf, int size, const char *base,
3380 const char *rel)
3381 {
3382 char *sep, *path_query;
3383 /* Absolute path, relative to the current server */
3384 if (base && strstr(base, "://") && rel[0] == '/') {
3385 if (base != buf)
3386 av_strlcpy(buf, base, size);
3387 sep = strstr(buf, "://");
3388 if (sep) {
3389 /* Take scheme from base url */
3390 if (rel[1] == '/') {
3391 sep[1] = '\0';
3392 } else {
3393 /* Take scheme and host from base url */
3394 sep += 3;
3395 sep = strchr(sep, '/');
3396 if (sep)
3397 *sep = '\0';
3398 }
3399 }
3400 av_strlcat(buf, rel, size);
3401 return;
3402 }
3403 /* If rel actually is an absolute url, just copy it */
3404 if (!base || strstr(rel, "://") || rel[0] == '/') {
3405 av_strlcpy(buf, rel, size);
3406 return;
3407 }
3408 if (base != buf)
3409 av_strlcpy(buf, base, size);
3410
3411 /* Strip off any query string from base */
3412 path_query = strchr(buf, '?');
3413 if (path_query != NULL)
3414 *path_query = '\0';
3415
3416 /* Is relative path just a new query part? */
3417 if (rel[0] == '?') {
3418 av_strlcat(buf, rel, size);
3419 return;
3420 }
3421
3422 /* Remove the file name from the base url */
3423 sep = strrchr(buf, '/');
3424 if (sep)
3425 sep[1] = '\0';
3426 else
3427 buf[0] = '\0';
3428 while (av_strstart(rel, "../", NULL) && sep) {
3429 /* Remove the path delimiter at the end */
3430 sep[0] = '\0';
3431 sep = strrchr(buf, '/');
3432 /* If the next directory name to pop off is "..", break here */
3433 if (!strcmp(sep ? &sep[1] : buf, "..")) {
3434 /* Readd the slash we just removed */
3435 av_strlcat(buf, "/", size);
3436 break;
3437 }
3438 /* Cut off the directory name */
3439 if (sep)
3440 sep[1] = '\0';
3441 else
3442 buf[0] = '\0';
3443 rel += 3;
3444 }
3445 av_strlcat(buf, rel, size);
3446 }
3447
3448 int64_t ff_iso8601_to_unix_time(const char *datestr)
3449 {
3450 #if HAVE_STRPTIME
3451 struct tm time1 = {0}, time2 = {0};
3452 char *ret1, *ret2;
3453 ret1 = strptime(datestr, "%Y - %m - %d %T", &time1);
3454 ret2 = strptime(datestr, "%Y - %m - %dT%T", &time2);
3455 if (ret2 && !ret1)
3456 return av_timegm(&time2);
3457 else
3458 return av_timegm(&time1);
3459 #else
3460 av_log(NULL, AV_LOG_WARNING, "strptime() unavailable on this system, cannot convert "
3461 "the date string.\n");
3462 return 0;
3463 #endif
3464 }
3465
3466 int avformat_query_codec(AVOutputFormat *ofmt, enum AVCodecID codec_id, int std_compliance)
3467 {
3468 if (ofmt) {
3469 if (ofmt->query_codec)
3470 return ofmt->query_codec(codec_id, std_compliance);
3471 else if (ofmt->codec_tag)
3472 return !!av_codec_get_tag(ofmt->codec_tag, codec_id);
3473 else if (codec_id == ofmt->video_codec || codec_id == ofmt->audio_codec ||
3474 codec_id == ofmt->subtitle_codec)
3475 return 1;
3476 }
3477 return AVERROR_PATCHWELCOME;
3478 }
3479
3480 int avformat_network_init(void)
3481 {
3482 #if CONFIG_NETWORK
3483 int ret;
3484 ff_network_inited_globally = 1;
3485 if ((ret = ff_network_init()) < 0)
3486 return ret;
3487 ff_tls_init();
3488 #endif
3489 return 0;
3490 }
3491
3492 int avformat_network_deinit(void)
3493 {
3494 #if CONFIG_NETWORK
3495 ff_network_close();
3496 ff_tls_deinit();
3497 #endif
3498 return 0;
3499 }
3500
3501 int ff_add_param_change(AVPacket *pkt, int32_t channels,
3502 uint64_t channel_layout, int32_t sample_rate,
3503 int32_t width, int32_t height)
3504 {
3505 uint32_t flags = 0;
3506 int size = 4;
3507 uint8_t *data;
3508 if (!pkt)
3509 return AVERROR(EINVAL);
3510 if (channels) {
3511 size += 4;
3512 flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT;
3513 }
3514 if (channel_layout) {
3515 size += 8;
3516 flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT;
3517 }
3518 if (sample_rate) {
3519 size += 4;
3520 flags |= AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE;
3521 }
3522 if (width || height) {
3523 size += 8;
3524 flags |= AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS;
3525 }
3526 data = av_packet_new_side_data(pkt, AV_PKT_DATA_PARAM_CHANGE, size);
3527 if (!data)
3528 return AVERROR(ENOMEM);
3529 bytestream_put_le32(&data, flags);
3530 if (channels)
3531 bytestream_put_le32(&data, channels);
3532 if (channel_layout)
3533 bytestream_put_le64(&data, channel_layout);
3534 if (sample_rate)
3535 bytestream_put_le32(&data, sample_rate);
3536 if (width || height) {
3537 bytestream_put_le32(&data, width);
3538 bytestream_put_le32(&data, height);
3539 }
3540 return 0;
3541 }
3542
3543 const struct AVCodecTag *avformat_get_riff_video_tags(void)
3544 {
3545 return ff_codec_bmp_tags;
3546 }
3547 const struct AVCodecTag *avformat_get_riff_audio_tags(void)
3548