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