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