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