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