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