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