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