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