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  bit_rate += st->codec->bit_rate;
1868  }
1869  ic->bit_rate = bit_rate;
1870  }
1871 
1872  /* if duration is already set, we believe it */
1873  if (ic->duration == AV_NOPTS_VALUE &&
1874  ic->bit_rate != 0) {
1875  filesize = ic->pb ? avio_size(ic->pb) : 0;
1876  if (filesize > 0) {
1877  for(i = 0; i < ic->nb_streams; i++) {
1878  st = ic->streams[i];
1879  duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);
1880  if (st->duration == AV_NOPTS_VALUE)
1881  st->duration = duration;
1882  }
1883  }
1884  }
1885 }
1886 
1887 #define DURATION_MAX_READ_SIZE 250000
1888 #define DURATION_MAX_RETRY 3
1889 
1890 /* only usable for MPEG-PS streams */
1891 static void estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
1892 {
1893  AVPacket pkt1, *pkt = &pkt1;
1894  AVStream *st;
1895  int read_size, i, ret;
1896  int64_t end_time;
1897  int64_t filesize, offset, duration;
1898  int retry=0;
1899 
1900  /* flush packet queue */
1901  flush_packet_queue(ic);
1902 
1903  for (i=0; i<ic->nb_streams; i++) {
1904  st = ic->streams[i];
1905  if (st->start_time == AV_NOPTS_VALUE && st->first_dts == AV_NOPTS_VALUE)
1906  av_log(st->codec, AV_LOG_WARNING, "start time is not set in estimate_timings_from_pts\n");
1907 
1908  if (st->parser) {
1909  av_parser_close(st->parser);
1910  st->parser= NULL;
1911  }
1912  }
1913 
1914  /* estimate the end time (duration) */
1915  /* XXX: may need to support wrapping */
1916  filesize = ic->pb ? avio_size(ic->pb) : 0;
1917  end_time = AV_NOPTS_VALUE;
1918  do{
1919  offset = filesize - (DURATION_MAX_READ_SIZE<<retry);
1920  if (offset < 0)
1921  offset = 0;
1922 
1923  avio_seek(ic->pb, offset, SEEK_SET);
1924  read_size = 0;
1925  for(;;) {
1926  if (read_size >= DURATION_MAX_READ_SIZE<<(FFMAX(retry-1,0)))
1927  break;
1928 
1929  do {
1930  ret = ff_read_packet(ic, pkt);
1931  } while(ret == AVERROR(EAGAIN));
1932  if (ret != 0)
1933  break;
1934  read_size += pkt->size;
1935  st = ic->streams[pkt->stream_index];
1936  if (pkt->pts != AV_NOPTS_VALUE &&
1937  (st->start_time != AV_NOPTS_VALUE ||
1938  st->first_dts != AV_NOPTS_VALUE)) {
1939  duration = end_time = pkt->pts;
1940  if (st->start_time != AV_NOPTS_VALUE)
1941  duration -= st->start_time;
1942  else
1943  duration -= st->first_dts;
1944  if (duration < 0)
1945  duration += 1LL<<st->pts_wrap_bits;
1946  if (duration > 0) {
1947  if (st->duration == AV_NOPTS_VALUE || st->duration < duration)
1948  st->duration = duration;
1949  }
1950  }
1951  av_free_packet(pkt);
1952  }
1953  }while( end_time==AV_NOPTS_VALUE
1954  && filesize > (DURATION_MAX_READ_SIZE<<retry)
1955  && ++retry <= DURATION_MAX_RETRY);
1956 
1958 
1959  avio_seek(ic->pb, old_offset, SEEK_SET);
1960  for (i=0; i<ic->nb_streams; i++) {
1961  st= ic->streams[i];
1962  st->cur_dts= st->first_dts;
1965  }
1966 }
1967 
1968 static void estimate_timings(AVFormatContext *ic, int64_t old_offset)
1969 {
1970  int64_t file_size;
1971 
1972  /* get the file size, if possible */
1973  if (ic->iformat->flags & AVFMT_NOFILE) {
1974  file_size = 0;
1975  } else {
1976  file_size = avio_size(ic->pb);
1977  file_size = FFMAX(0, file_size);
1978  }
1979 
1980  if ((!strcmp(ic->iformat->name, "mpeg") ||
1981  !strcmp(ic->iformat->name, "mpegts")) &&
1982  file_size && ic->pb->seekable) {
1983  /* get accurate estimate from the PTSes */
1984  estimate_timings_from_pts(ic, old_offset);
1985  } else if (has_duration(ic)) {
1986  /* at least one component has timings - we use them for all
1987  the components */
1989  } else {
1990  av_log(ic, AV_LOG_WARNING, "Estimating duration from bitrate, this may be inaccurate\n");
1991  /* less precise: use bitrate info */
1993  }
1995 
1996  {
1997  int i;
1998  AVStream av_unused *st;
1999  for(i = 0;i < ic->nb_streams; i++) {
2000  st = ic->streams[i];
2001  av_dlog(ic, "%d: start_time: %0.3f duration: %0.3f\n", i,
2002  (double) st->start_time / AV_TIME_BASE,
2003  (double) st->duration / AV_TIME_BASE);
2004  }
2005  av_dlog(ic, "stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
2006  (double) ic->start_time / AV_TIME_BASE,
2007  (double) ic->duration / AV_TIME_BASE,
2008  ic->bit_rate / 1000);
2009  }
2010 }
2011 
2013 {
2014  AVCodecContext *avctx = st->codec;
2015  int val;
2016  switch (avctx->codec_type) {
2017  case AVMEDIA_TYPE_AUDIO:
2018  val = avctx->sample_rate && avctx->channels;
2019  if (st->info->found_decoder >= 0 && avctx->sample_fmt == AV_SAMPLE_FMT_NONE)
2020  return 0;
2021  break;
2022  case AVMEDIA_TYPE_VIDEO:
2023  val = avctx->width;
2024  if (st->info->found_decoder >= 0 && avctx->pix_fmt == AV_PIX_FMT_NONE)
2025  return 0;
2026  break;
2027  default:
2028  val = 1;
2029  break;
2030  }
2031  return avctx->codec_id != AV_CODEC_ID_NONE && val != 0;
2032 }
2033 
2035 {
2036  return st->codec->codec_id != AV_CODEC_ID_H264 ||
2037  st->info->nb_decoded_frames >= 6;
2038 }
2039 
2040 /* returns 1 or 0 if or if not decoded data was returned, or a negative error */
2042 {
2043  const AVCodec *codec;
2044  int got_picture = 1, ret = 0;
2045  AVFrame *frame = avcodec_alloc_frame();
2046  AVPacket pkt = *avpkt;
2047 
2048  if (!frame)
2049  return AVERROR(ENOMEM);
2050 
2051  if (!avcodec_is_open(st->codec) && !st->info->found_decoder) {
2052  AVDictionary *thread_opt = NULL;
2053 
2054  codec = st->codec->codec ? st->codec->codec :
2056 
2057  if (!codec) {
2058  st->info->found_decoder = -1;
2059  ret = -1;
2060  goto fail;
2061  }
2062 
2063  /* force thread count to 1 since the h264 decoder will not extract SPS
2064  * and PPS to extradata during multi-threaded decoding */
2065  av_dict_set(options ? options : &thread_opt, "threads", "1", 0);
2066  ret = avcodec_open2(st->codec, codec, options ? options : &thread_opt);
2067  if (!options)
2068  av_dict_free(&thread_opt);
2069  if (ret < 0) {
2070  st->info->found_decoder = -1;
2071  goto fail;
2072  }
2073  st->info->found_decoder = 1;
2074  } else if (!st->info->found_decoder)
2075  st->info->found_decoder = 1;
2076 
2077  if (st->info->found_decoder < 0) {
2078  ret = -1;
2079  goto fail;
2080  }
2081 
2082  while ((pkt.size > 0 || (!pkt.data && got_picture)) &&
2083  ret >= 0 &&
2084  (!has_codec_parameters(st) ||
2087  got_picture = 0;
2089  switch(st->codec->codec_type) {
2090  case AVMEDIA_TYPE_VIDEO:
2091  ret = avcodec_decode_video2(st->codec, frame,
2092  &got_picture, &pkt);
2093  break;
2094  case AVMEDIA_TYPE_AUDIO:
2095  ret = avcodec_decode_audio4(st->codec, frame, &got_picture, &pkt);
2096  break;
2097  default:
2098  break;
2099  }
2100  if (ret >= 0) {
2101  if (got_picture)
2102  st->info->nb_decoded_frames++;
2103  pkt.data += ret;
2104  pkt.size -= ret;
2105  ret = got_picture;
2106  }
2107  }
2108 
2109 fail:
2110  avcodec_free_frame(&frame);
2111  return ret;
2112 }
2113 
2114 unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum AVCodecID id)
2115 {
2116  while (tags->id != AV_CODEC_ID_NONE) {
2117  if (tags->id == id)
2118  return tags->tag;
2119  tags++;
2120  }
2121  return 0;
2122 }
2123 
2124 enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
2125 {
2126  int i;
2127  for(i=0; tags[i].id != AV_CODEC_ID_NONE;i++) {
2128  if(tag == tags[i].tag)
2129  return tags[i].id;
2130  }
2131  for(i=0; tags[i].id != AV_CODEC_ID_NONE; i++) {
2132  if (avpriv_toupper4(tag) == avpriv_toupper4(tags[i].tag))
2133  return tags[i].id;
2134  }
2135  return AV_CODEC_ID_NONE;
2136 }
2137 
2138 enum AVCodecID ff_get_pcm_codec_id(int bps, int flt, int be, int sflags)
2139 {
2140  if (flt) {
2141  switch (bps) {
2142  case 32: return be ? AV_CODEC_ID_PCM_F32BE : AV_CODEC_ID_PCM_F32LE;
2143  case 64: return be ? AV_CODEC_ID_PCM_F64BE : AV_CODEC_ID_PCM_F64LE;
2144  default: return AV_CODEC_ID_NONE;
2145  }
2146  } else {
2147  bps >>= 3;
2148  if (sflags & (1 << (bps - 1))) {
2149  switch (bps) {
2150  case 1: return AV_CODEC_ID_PCM_S8;
2151  case 2: return be ? AV_CODEC_ID_PCM_S16BE : AV_CODEC_ID_PCM_S16LE;
2152  case 3: return be ? AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
2153  case 4: return be ? AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
2154  default: return AV_CODEC_ID_NONE;
2155  }
2156  } else {
2157  switch (bps) {
2158  case 1: return AV_CODEC_ID_PCM_U8;
2159  case 2: return be ? AV_CODEC_ID_PCM_U16BE : AV_CODEC_ID_PCM_U16LE;
2160  case 3: return be ? AV_CODEC_ID_PCM_U24BE : AV_CODEC_ID_PCM_U24LE;
2161  case 4: return be ? AV_CODEC_ID_PCM_U32BE : AV_CODEC_ID_PCM_U32LE;
2162  default: return AV_CODEC_ID_NONE;
2163  }
2164  }
2165  }
2166 }
2167 
2168 unsigned int av_codec_get_tag(const AVCodecTag * const *tags, enum AVCodecID id)
2169 {
2170  int i;
2171  for(i=0; tags && tags[i]; i++){
2172  int tag= ff_codec_get_tag(tags[i], id);
2173  if(tag) return tag;
2174  }
2175  return 0;
2176 }
2177 
2178 enum AVCodecID av_codec_get_id(const AVCodecTag * const *tags, unsigned int tag)
2179 {
2180  int i;
2181  for(i=0; tags && tags[i]; i++){
2182  enum AVCodecID id= ff_codec_get_id(tags[i], tag);
2183  if(id!=AV_CODEC_ID_NONE) return id;
2184  }
2185  return AV_CODEC_ID_NONE;
2186 }
2187 
2189 {
2190  unsigned int i, j;
2191  int64_t max_time = s->duration + ((s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time);
2192 
2193  for (i = 0; i < s->nb_chapters; i++)
2194  if (s->chapters[i]->end == AV_NOPTS_VALUE) {
2195  AVChapter *ch = s->chapters[i];
2196  int64_t end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q, ch->time_base)
2197  : INT64_MAX;
2198 
2199  for (j = 0; j < s->nb_chapters; j++) {
2200  AVChapter *ch1 = s->chapters[j];
2201  int64_t next_start = av_rescale_q(ch1->start, ch1->time_base, ch->time_base);
2202  if (j != i && next_start > ch->start && next_start < end)
2203  end = next_start;
2204  }
2205  ch->end = (end == INT64_MAX) ? ch->start : end;
2206  }
2207 }
2208 
2209 static int get_std_framerate(int i){
2210  if(i<60*12) return i*1001;
2211  else return ((const int[]){24,30,60,12,15})[i-60*12]*1000*12;
2212 }
2213 
2214 /*
2215  * Is the time base unreliable.
2216  * This is a heuristic to balance between quick acceptance of the values in
2217  * the headers vs. some extra checks.
2218  * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
2219  * MPEG-2 commonly misuses field repeat flags to store different framerates.
2220  * And there are "variable" fps files this needs to detect as well.
2221  */
2223  if( c->time_base.den >= 101L*c->time_base.num
2224  || c->time_base.den < 5L*c->time_base.num
2225 /* || c->codec_tag == AV_RL32("DIVX")
2226  || c->codec_tag == AV_RL32("XVID")*/
2228  || c->codec_id == AV_CODEC_ID_H264
2229  )
2230  return 1;
2231  return 0;
2232 }
2233 
2235 {
2236  int i, count, ret, read_size, j;
2237  AVStream *st;
2238  AVPacket pkt1, *pkt;
2239  int64_t old_offset = avio_tell(ic->pb);
2240  int orig_nb_streams = ic->nb_streams; // new streams might appear, no options for those
2241 
2242  for(i=0;i<ic->nb_streams;i++) {
2243  const AVCodec *codec;
2244  AVDictionary *thread_opt = NULL;
2245  st = ic->streams[i];
2246 
2247  //only for the split stuff
2248  if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE)) {
2249  st->parser = av_parser_init(st->codec->codec_id);
2250  if(st->need_parsing == AVSTREAM_PARSE_HEADERS && st->parser){
2252  }
2253  }
2254  codec = st->codec->codec ? st->codec->codec :
2256 
2257  /* force thread count to 1 since the h264 decoder will not extract SPS
2258  * and PPS to extradata during multi-threaded decoding */
2259  av_dict_set(options ? &options[i] : &thread_opt, "threads", "1", 0);
2260 
2261  /* Ensure that subtitle_header is properly set. */
2263  && codec && !st->codec->codec)
2264  avcodec_open2(st->codec, codec, options ? &options[i]
2265  : &thread_opt);
2266 
2267  //try to just open decoders, in case this is enough to get parameters
2268  if (!has_codec_parameters(st)) {
2269  if (codec && !st->codec->codec)
2270  avcodec_open2(st->codec, codec, options ? &options[i]
2271  : &thread_opt);
2272  }
2273  if (!options)
2274  av_dict_free(&thread_opt);
2275  }
2276 
2277  for (i=0; i<ic->nb_streams; i++) {
2278 #if FF_API_R_FRAME_RATE
2279  ic->streams[i]->info->last_dts = AV_NOPTS_VALUE;
2280 #endif
2283  }
2284 
2285  count = 0;
2286  read_size = 0;
2287  for(;;) {
2289  ret= AVERROR_EXIT;
2290  av_log(ic, AV_LOG_DEBUG, "interrupted\n");
2291  break;
2292  }
2293 
2294  /* check if one codec still needs to be handled */
2295  for(i=0;i<ic->nb_streams;i++) {
2296  int fps_analyze_framecount = 20;
2297 
2298  st = ic->streams[i];
2299  if (!has_codec_parameters(st))
2300  break;
2301  /* if the timebase is coarse (like the usual millisecond precision
2302  of mkv), we need to analyze more frames to reliably arrive at
2303  the correct fps */
2304  if (av_q2d(st->time_base) > 0.0005)
2305  fps_analyze_framecount *= 2;
2306  if (ic->fps_probe_size >= 0)
2307  fps_analyze_framecount = ic->fps_probe_size;
2308  /* variable fps and no guess at the real fps */
2309  if( tb_unreliable(st->codec) && !st->avg_frame_rate.num
2310  && st->codec_info_nb_frames < fps_analyze_framecount
2311  && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2312  break;
2313  if(st->parser && st->parser->parser->split && !st->codec->extradata)
2314  break;
2315  if (st->first_dts == AV_NOPTS_VALUE &&
2316  (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2318  break;
2319  }
2320  if (i == ic->nb_streams) {
2321  /* NOTE: if the format has no header, then we need to read
2322  some packets to get most of the streams, so we cannot
2323  stop here */
2324  if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
2325  /* if we found the info for all the codecs, we can stop */
2326  ret = count;
2327  av_log(ic, AV_LOG_DEBUG, "All info found\n");
2328  break;
2329  }
2330  }
2331  /* we did not get all the codec info, but we read too much data */
2332  if (read_size >= ic->probesize) {
2333  ret = count;
2334  av_log(ic, AV_LOG_DEBUG, "Probe buffer size limit %d reached\n", ic->probesize);
2335  break;
2336  }
2337 
2338  /* NOTE: a new stream can be added there if no header in file
2339  (AVFMTCTX_NOHEADER) */
2340  ret = read_frame_internal(ic, &pkt1);
2341  if (ret == AVERROR(EAGAIN))
2342  continue;
2343 
2344  if (ret < 0) {
2345  /* EOF or error*/
2346  AVPacket empty_pkt = { 0 };
2347  int err = 0;
2348  av_init_packet(&empty_pkt);
2349 
2350  ret = -1; /* we could not have all the codec parameters before EOF */
2351  for(i=0;i<ic->nb_streams;i++) {
2352  st = ic->streams[i];
2353 
2354  /* flush the decoders */
2355  if (st->info->found_decoder == 1) {
2356  do {
2357  err = try_decode_frame(st, &empty_pkt,
2358  (options && i < orig_nb_streams) ?
2359  &options[i] : NULL);
2360  } while (err > 0 && !has_codec_parameters(st));
2361  }
2362 
2363  if (err < 0) {
2364  av_log(ic, AV_LOG_WARNING,
2365  "decoding for stream %d failed\n", st->index);
2366  } else if (!has_codec_parameters(st)) {
2367  char buf[256];
2368  avcodec_string(buf, sizeof(buf), st->codec, 0);
2369  av_log(ic, AV_LOG_WARNING,
2370  "Could not find codec parameters (%s)\n", buf);
2371  } else {
2372  ret = 0;
2373  }
2374  }
2375  break;
2376  }
2377 
2378  if (ic->flags & AVFMT_FLAG_NOBUFFER) {
2379  pkt = &pkt1;
2380  } else {
2381  pkt = add_to_pktbuf(&ic->packet_buffer, &pkt1,
2382  &ic->packet_buffer_end);
2383  if ((ret = av_dup_packet(pkt)) < 0)
2384  goto find_stream_info_err;
2385  }
2386 
2387  read_size += pkt->size;
2388 
2389  st = ic->streams[pkt->stream_index];
2390  if (pkt->dts != AV_NOPTS_VALUE && st->codec_info_nb_frames > 1) {
2391  /* check for non-increasing dts */
2392  if (st->info->fps_last_dts != AV_NOPTS_VALUE &&
2393  st->info->fps_last_dts >= pkt->dts) {
2394  av_log(ic, AV_LOG_WARNING, "Non-increasing DTS in stream %d: "
2395  "packet %d with DTS %"PRId64", packet %d with DTS "
2396  "%"PRId64"\n", st->index, st->info->fps_last_dts_idx,
2397  st->info->fps_last_dts, st->codec_info_nb_frames, pkt->dts);
2399  }
2400  /* check for a discontinuity in dts - if the difference in dts
2401  * is more than 1000 times the average packet duration in the sequence,
2402  * we treat it as a discontinuity */
2403  if (st->info->fps_last_dts != AV_NOPTS_VALUE &&
2405  (pkt->dts - st->info->fps_last_dts) / 1000 >
2407  av_log(ic, AV_LOG_WARNING, "DTS discontinuity in stream %d: "
2408  "packet %d with DTS %"PRId64", packet %d with DTS "
2409  "%"PRId64"\n", st->index, st->info->fps_last_dts_idx,
2410  st->info->fps_last_dts, st->codec_info_nb_frames, pkt->dts);
2412  }
2413 
2414  /* update stored dts values */
2415  if (st->info->fps_first_dts == AV_NOPTS_VALUE) {
2416  st->info->fps_first_dts = pkt->dts;
2418  }
2419  st->info->fps_last_dts = pkt->dts;
2421 
2422  /* check max_analyze_duration */
2423  if (av_rescale_q(pkt->dts - st->info->fps_first_dts, st->time_base,
2425  av_log(ic, AV_LOG_WARNING, "max_analyze_duration reached\n");
2426  break;
2427  }
2428  }
2429 #if FF_API_R_FRAME_RATE
2430  {
2431  int64_t last = st->info->last_dts;
2432 
2433  if(pkt->dts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && pkt->dts > last){
2434  int64_t duration= pkt->dts - last;
2435  double dur= duration * av_q2d(st->time_base);
2436 
2437  if (st->info->duration_count < 2)
2438  memset(st->info->duration_error, 0, sizeof(st->info->duration_error));
2439  for (i=1; i<FF_ARRAY_ELEMS(st->info->duration_error); i++) {
2440  int framerate= get_std_framerate(i);
2441  int ticks= lrintf(dur*framerate/(1001*12));
2442  double error = dur - (double)ticks*1001*12 / framerate;
2443  st->info->duration_error[i] += error*error;
2444  }
2445  st->info->duration_count++;
2446  // ignore the first 4 values, they might have some random jitter
2447  if (st->info->duration_count > 3)
2448  st->info->duration_gcd = av_gcd(st->info->duration_gcd, duration);
2449  }
2450  if (last == AV_NOPTS_VALUE || st->info->duration_count <= 1)
2451  st->info->last_dts = pkt->dts;
2452  }
2453 #endif
2454  if(st->parser && st->parser->parser->split && !st->codec->extradata){
2455  int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
2456  if (i > 0 && i < FF_MAX_EXTRADATA_SIZE) {
2457  st->codec->extradata_size= i;
2459  if (!st->codec->extradata)
2460  return AVERROR(ENOMEM);
2461  memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);
2462  memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2463  }
2464  }
2465 
2466  /* if still no information, we try to open the codec and to
2467  decompress the frame. We try to avoid that in most cases as
2468  it takes longer and uses more memory. For MPEG-4, we need to
2469  decompress for QuickTime.
2470 
2471  If CODEC_CAP_CHANNEL_CONF is set this will force decoding of at
2472  least one frame of codec data, this makes sure the codec initializes
2473  the channel configuration and does not only trust the values from the container.
2474  */
2475  try_decode_frame(st, pkt, (options && i < orig_nb_streams ) ? &options[i] : NULL);
2476 
2477  st->codec_info_nb_frames++;
2478  count++;
2479  }
2480 
2481  // close codecs which were opened in try_decode_frame()
2482  for(i=0;i<ic->nb_streams;i++) {
2483  st = ic->streams[i];
2484  avcodec_close(st->codec);
2485  }
2486  for(i=0;i<ic->nb_streams;i++) {
2487  st = ic->streams[i];
2488  if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2489  /* estimate average framerate if not set by demuxer */
2490  if (!st->avg_frame_rate.num && st->info->fps_last_dts != st->info->fps_first_dts) {
2491  int64_t delta_dts = st->info->fps_last_dts - st->info->fps_first_dts;
2492  int delta_packets = st->info->fps_last_dts_idx - st->info->fps_first_dts_idx;
2493  int best_fps = 0;
2494  double best_error = 0.01;
2495 
2497  delta_packets*(int64_t)st->time_base.den,
2498  delta_dts*(int64_t)st->time_base.num, 60000);
2499 
2500  /* round guessed framerate to a "standard" framerate if it's
2501  * within 1% of the original estimate*/
2502  for (j = 1; j < MAX_STD_TIMEBASES; j++) {
2503  AVRational std_fps = { get_std_framerate(j), 12*1001 };
2504  double error = fabs(av_q2d(st->avg_frame_rate) / av_q2d(std_fps) - 1);
2505 
2506  if (error < best_error) {
2507  best_error = error;
2508  best_fps = std_fps.num;
2509  }
2510  }
2511  if (best_fps) {
2513  best_fps, 12*1001, INT_MAX);
2514  }
2515  }
2516 #if FF_API_R_FRAME_RATE
2517  // the check for tb_unreliable() is not completely correct, since this is not about handling
2518  // a unreliable/inexact time base, but a time base that is finer than necessary, as e.g.
2519  // ipmovie.c produces.
2520  if (tb_unreliable(st->codec) && st->info->duration_count > 15 && st->info->duration_gcd > 1 && !st->r_frame_rate.num)
2521  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);
2522  if (st->info->duration_count && !st->r_frame_rate.num
2523  && tb_unreliable(st->codec)) {
2524  int num = 0;
2525  double best_error= 2*av_q2d(st->time_base);
2526  best_error = best_error*best_error*st->info->duration_count*1000*12*30;
2527 
2528  for (j=1; j<FF_ARRAY_ELEMS(st->info->duration_error); j++) {
2529  double error = st->info->duration_error[j] * get_std_framerate(j);
2530  if(error < best_error){
2531  best_error= error;
2532  num = get_std_framerate(j);
2533  }
2534  }
2535  // do not increase frame rate by more than 1 % in order to match a standard rate.
2536  if (num && (!st->r_frame_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(st->r_frame_rate)))
2537  av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX);
2538  }
2539 #endif
2540  }else if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2541  if(!st->codec->bits_per_coded_sample)
2543  // set stream disposition based on audio service type
2544  switch (st->codec->audio_service_type) {
2552  st->disposition = AV_DISPOSITION_COMMENT; break;
2554  st->disposition = AV_DISPOSITION_KARAOKE; break;
2555  }
2556  }
2557  }
2558 
2559  estimate_timings(ic, old_offset);
2560 
2562 
2563  find_stream_info_err:
2564  for (i=0; i < ic->nb_streams; i++) {
2565  if (ic->streams[i]->codec)
2566  ic->streams[i]->codec->thread_count = 0;
2567  av_freep(&ic->streams[i]->info);
2568  }
2569  return ret;
2570 }
2571 
2573 {
2574  int i, j;
2575 
2576  for (i = 0; i < ic->nb_programs; i++)
2577  for (j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
2578  if (ic->programs[i]->stream_index[j] == s)
2579  return ic->programs[i];
2580  return NULL;
2581 }
2582 
2584  enum AVMediaType type,
2585  int wanted_stream_nb,
2586  int related_stream,
2587  AVCodec **decoder_ret,
2588  int flags)
2589 {
2590  int i, nb_streams = ic->nb_streams;
2591  int ret = AVERROR_STREAM_NOT_FOUND, best_count = -1;
2592  unsigned *program = NULL;
2593  AVCodec *decoder = NULL, *best_decoder = NULL;
2594 
2595  if (related_stream >= 0 && wanted_stream_nb < 0) {
2596  AVProgram *p = find_program_from_stream(ic, related_stream);
2597  if (p) {
2598  program = p->stream_index;
2599  nb_streams = p->nb_stream_indexes;
2600  }
2601  }
2602  for (i = 0; i < nb_streams; i++) {
2603  int real_stream_index = program ? program[i] : i;
2604  AVStream *st = ic->streams[real_stream_index];
2605  AVCodecContext *avctx = st->codec;
2606  if (avctx->codec_type != type)
2607  continue;
2608  if (wanted_stream_nb >= 0 && real_stream_index != wanted_stream_nb)
2609  continue;
2611  continue;
2612  if (decoder_ret) {
2613  decoder = avcodec_find_decoder(st->codec->codec_id);
2614  if (!decoder) {
2615  if (ret < 0)
2617  continue;
2618  }
2619  }
2620  if (best_count >= st->codec_info_nb_frames)
2621  continue;
2622  best_count = st->codec_info_nb_frames;
2623  ret = real_stream_index;
2624  best_decoder = decoder;
2625  if (program && i == nb_streams - 1 && ret < 0) {
2626  program = NULL;
2627  nb_streams = ic->nb_streams;
2628  i = 0; /* no related stream found, try again with everything */
2629  }
2630  }
2631  if (decoder_ret)
2632  *decoder_ret = best_decoder;
2633  return ret;
2634 }
2635 
2636 /*******************************************************/
2637 
2639 {
2640  if (s->iformat->read_play)
2641  return s->iformat->read_play(s);
2642  if (s->pb)
2643  return avio_pause(s->pb, 0);
2644  return AVERROR(ENOSYS);
2645 }
2646 
2648 {
2649  if (s->iformat->read_pause)
2650  return s->iformat->read_pause(s);
2651  if (s->pb)
2652  return avio_pause(s->pb, 1);
2653  return AVERROR(ENOSYS);
2654 }
2655 
2657 {
2658  int i;
2659  AVStream *st;
2660 
2661  av_opt_free(s);
2662  if (s->iformat && s->iformat->priv_class && s->priv_data)
2663  av_opt_free(s->priv_data);
2664 
2665  for(i=0;i<s->nb_streams;i++) {
2666  /* free all data in a stream component */
2667  st = s->streams[i];
2668  if (st->parser) {
2669  av_parser_close(st->parser);
2670  }
2671  if (st->attached_pic.data)
2673  av_dict_free(&st->metadata);
2674  av_freep(&st->probe_data.buf);
2675  av_free(st->index_entries);
2676  av_free(st->codec->extradata);
2678  av_free(st->codec);
2679  av_free(st->priv_data);
2680  av_free(st->info);
2681  av_free(st);
2682  }
2683  for(i=s->nb_programs-1; i>=0; i--) {
2684  av_dict_free(&s->programs[i]->metadata);
2685  av_freep(&s->programs[i]->stream_index);
2686  av_freep(&s->programs[i]);
2687  }
2688  av_freep(&s->programs);
2689  av_freep(&s->priv_data);
2690  while(s->nb_chapters--) {
2692  av_free(s->chapters[s->nb_chapters]);
2693  }
2694  av_freep(&s->chapters);
2695  av_dict_free(&s->metadata);
2696  av_freep(&s->streams);
2697  av_free(s);
2698 }
2699 
2700 #if FF_API_CLOSE_INPUT_FILE
2701 void av_close_input_file(AVFormatContext *s)
2702 {
2704 }
2705 #endif
2706 
2708 {
2709  AVFormatContext *s = *ps;
2710  AVIOContext *pb = s->pb;
2711 
2712  if ((s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
2713  (s->flags & AVFMT_FLAG_CUSTOM_IO))
2714  pb = NULL;
2715 
2716  flush_packet_queue(s);
2717 
2718  if (s->iformat) {
2719  if (s->iformat->read_close)
2720  s->iformat->read_close(s);
2721  }
2722 
2724 
2725  *ps = NULL;
2726 
2727  avio_close(pb);
2728 }
2729 
2731 {
2732  AVStream *st;
2733  int i;
2734  AVStream **streams;
2735 
2736  if (s->nb_streams >= INT_MAX/sizeof(*streams))
2737  return NULL;
2738  streams = av_realloc(s->streams, (s->nb_streams + 1) * sizeof(*streams));
2739  if (!streams)
2740  return NULL;
2741  s->streams = streams;
2742 
2743  st = av_mallocz(sizeof(AVStream));
2744  if (!st)
2745  return NULL;
2746  if (!(st->info = av_mallocz(sizeof(*st->info)))) {
2747  av_free(st);
2748  return NULL;
2749  }
2750 
2751  st->codec = avcodec_alloc_context3(c);
2752  if (s->iformat) {
2753  /* no default bitrate if decoding */
2754  st->codec->bit_rate = 0;
2755  }
2756  st->index = s->nb_streams;
2757  st->start_time = AV_NOPTS_VALUE;
2758  st->duration = AV_NOPTS_VALUE;
2759  /* we set the current DTS to 0 so that formats without any timestamps
2760  but durations get some timestamps, formats with some unknown
2761  timestamps have their first few packets buffered and the
2762  timestamps corrected before they are returned to the user */
2763  st->cur_dts = 0;
2764  st->first_dts = AV_NOPTS_VALUE;
2766 
2767  /* default pts setting is MPEG-like */
2768  avpriv_set_pts_info(st, 33, 1, 90000);
2770  for(i=0; i<MAX_REORDER_DELAY+1; i++)
2771  st->pts_buffer[i]= AV_NOPTS_VALUE;
2773 
2774  st->sample_aspect_ratio = (AVRational){0,1};
2775 
2776 #if FF_API_R_FRAME_RATE
2777  st->info->last_dts = AV_NOPTS_VALUE;
2778 #endif
2781 
2782  s->streams[s->nb_streams++] = st;
2783  return st;
2784 }
2785 
2787 {
2788  AVProgram *program=NULL;
2789  int i;
2790 
2791  av_dlog(ac, "new_program: id=0x%04x\n", id);
2792 
2793  for(i=0; i<ac->nb_programs; i++)
2794  if(ac->programs[i]->id == id)
2795  program = ac->programs[i];
2796 
2797  if(!program){
2798  program = av_mallocz(sizeof(AVProgram));
2799  if (!program)
2800  return NULL;
2801  dynarray_add(&ac->programs, &ac->nb_programs, program);
2802  program->discard = AVDISCARD_NONE;
2803  }
2804  program->id = id;
2805 
2806  return program;
2807 }
2808 
2809 AVChapter *avpriv_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title)
2810 {
2811  AVChapter *chapter = NULL;
2812  int i;
2813 
2814  for(i=0; i<s->nb_chapters; i++)
2815  if(s->chapters[i]->id == id)
2816  chapter = s->chapters[i];
2817 
2818  if(!chapter){
2819  chapter= av_mallocz(sizeof(AVChapter));
2820  if(!chapter)
2821  return NULL;
2822  dynarray_add(&s->chapters, &s->nb_chapters, chapter);
2823  }
2824  av_dict_set(&chapter->metadata, "title", title, 0);
2825  chapter->id = id;
2826  chapter->time_base= time_base;
2827  chapter->start = start;
2828  chapter->end = end;
2829 
2830  return chapter;
2831 }
2832 
2833 void ff_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx)
2834 {
2835  int i, j;
2836  AVProgram *program=NULL;
2837  void *tmp;
2838 
2839  if (idx >= ac->nb_streams) {
2840  av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
2841  return;
2842  }
2843 
2844  for(i=0; i<ac->nb_programs; i++){
2845  if(ac->programs[i]->id != progid)
2846  continue;
2847  program = ac->programs[i];
2848  for(j=0; j<program->nb_stream_indexes; j++)
2849  if(program->stream_index[j] == idx)
2850  return;
2851 
2852  tmp = av_realloc(program->stream_index, sizeof(unsigned int)*(program->nb_stream_indexes+1));
2853  if(!tmp)
2854  return;
2855  program->stream_index = tmp;
2856  program->stream_index[program->nb_stream_indexes++] = idx;
2857  return;
2858  }
2859 }
2860 
2861 static void print_fps(double d, const char *postfix){
2862  uint64_t v= lrintf(d*100);
2863  if (v% 100 ) av_log(NULL, AV_LOG_INFO, ", %3.2f %s", d, postfix);
2864  else if(v%(100*1000)) av_log(NULL, AV_LOG_INFO, ", %1.0f %s", d, postfix);
2865  else av_log(NULL, AV_LOG_INFO, ", %1.0fk %s", d/1000, postfix);
2866 }
2867 
2868 static void dump_metadata(void *ctx, AVDictionary *m, const char *indent)
2869 {
2870  if(m && !(av_dict_count(m) == 1 && av_dict_get(m, "language", NULL, 0))){
2872 
2873  av_log(ctx, AV_LOG_INFO, "%sMetadata:\n", indent);
2874  while((tag=av_dict_get(m, "", tag, AV_DICT_IGNORE_SUFFIX))) {
2875  if(strcmp("language", tag->key))
2876  av_log(ctx, AV_LOG_INFO, "%s %-16s: %s\n", indent, tag->key, tag->value);
2877  }
2878  }
2879 }
2880 
2881 /* "user interface" functions */
2882 static void dump_stream_format(AVFormatContext *ic, int i, int index, int is_output)
2883 {
2884  char buf[256];
2885  int flags = (is_output ? ic->oformat->flags : ic->iformat->flags);
2886  AVStream *st = ic->streams[i];
2887  int g = av_gcd(st->time_base.num, st->time_base.den);
2888  AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL, 0);
2889  avcodec_string(buf, sizeof(buf), st->codec, is_output);
2890  av_log(NULL, AV_LOG_INFO, " Stream #%d.%d", index, i);
2891  /* the pid is an important information, so we display it */
2892  /* XXX: add a generic system */
2893  if (flags & AVFMT_SHOW_IDS)
2894  av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
2895  if (lang)
2896  av_log(NULL, AV_LOG_INFO, "(%s)", lang->value);
2897  av_log(NULL, AV_LOG_DEBUG, ", %d, %d/%d", st->codec_info_nb_frames, st->time_base.num/g, st->time_base.den/g);
2898  av_log(NULL, AV_LOG_INFO, ": %s", buf);
2899  if (st->sample_aspect_ratio.num && // default
2901  AVRational display_aspect_ratio;
2902  av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
2905  1024*1024);
2906  av_log(NULL, AV_LOG_INFO, ", PAR %d:%d DAR %d:%d",
2908  display_aspect_ratio.num, display_aspect_ratio.den);
2909  }
2910  if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO){
2911  if(st->avg_frame_rate.den && st->avg_frame_rate.num)
2912  print_fps(av_q2d(st->avg_frame_rate), "fps");
2913 #if FF_API_R_FRAME_RATE
2914  if(st->r_frame_rate.den && st->r_frame_rate.num)
2915  print_fps(av_q2d(st->r_frame_rate), "tbr");
2916 #endif
2917  if(st->time_base.den && st->time_base.num)
2918  print_fps(1/av_q2d(st->time_base), "tbn");
2919  if(st->codec->time_base.den && st->codec->time_base.num)
2920  print_fps(1/av_q2d(st->codec->time_base), "tbc");
2921  }
2923  av_log(NULL, AV_LOG_INFO, " (default)");
2924  if (st->disposition & AV_DISPOSITION_DUB)
2925  av_log(NULL, AV_LOG_INFO, " (dub)");
2927  av_log(NULL, AV_LOG_INFO, " (original)");
2929  av_log(NULL, AV_LOG_INFO, " (comment)");
2931  av_log(NULL, AV_LOG_INFO, " (lyrics)");
2933  av_log(NULL, AV_LOG_INFO, " (karaoke)");
2935  av_log(NULL, AV_LOG_INFO, " (forced)");
2937  av_log(NULL, AV_LOG_INFO, " (hearing impaired)");
2939  av_log(NULL, AV_LOG_INFO, " (visual impaired)");
2941  av_log(NULL, AV_LOG_INFO, " (clean effects)");
2942  av_log(NULL, AV_LOG_INFO, "\n");
2943  dump_metadata(NULL, st->metadata, " ");
2944 }
2945 
2947  int index,
2948  const char *url,
2949  int is_output)
2950 {
2951  int i;
2952  uint8_t *printed = ic->nb_streams ? av_mallocz(ic->nb_streams) : NULL;
2953  if (ic->nb_streams && !printed)
2954  return;
2955 
2956  av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",
2957  is_output ? "Output" : "Input",
2958  index,
2959  is_output ? ic->oformat->name : ic->iformat->name,
2960  is_output ? "to" : "from", url);
2961  dump_metadata(NULL, ic->metadata, " ");
2962  if (!is_output) {
2963  av_log(NULL, AV_LOG_INFO, " Duration: ");
2964  if (ic->duration != AV_NOPTS_VALUE) {
2965  int hours, mins, secs, us;
2966  secs = ic->duration / AV_TIME_BASE;
2967  us = ic->duration % AV_TIME_BASE;
2968  mins = secs / 60;
2969  secs %= 60;
2970  hours = mins / 60;
2971  mins %= 60;
2972  av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%02d", hours, mins, secs,
2973  (100 * us) / AV_TIME_BASE);
2974  } else {
2975  av_log(NULL, AV_LOG_INFO, "N/A");
2976  }
2977  if (ic->start_time != AV_NOPTS_VALUE) {
2978  int secs, us;
2979  av_log(NULL, AV_LOG_INFO, ", start: ");
2980  secs = ic->start_time / AV_TIME_BASE;
2981  us = abs(ic->start_time % AV_TIME_BASE);
2982  av_log(NULL, AV_LOG_INFO, "%d.%06d",
2983  secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));
2984  }
2985  av_log(NULL, AV_LOG_INFO, ", bitrate: ");
2986  if (ic->bit_rate) {
2987  av_log(NULL, AV_LOG_INFO,"%d kb/s", ic->bit_rate / 1000);
2988  } else {
2989  av_log(NULL, AV_LOG_INFO, "N/A");
2990  }
2991  av_log(NULL, AV_LOG_INFO, "\n");
2992  }
2993  for (i = 0; i < ic->nb_chapters; i++) {
2994  AVChapter *ch = ic->chapters[i];
2995  av_log(NULL, AV_LOG_INFO, " Chapter #%d.%d: ", index, i);
2996  av_log(NULL, AV_LOG_INFO, "start %f, ", ch->start * av_q2d(ch->time_base));
2997  av_log(NULL, AV_LOG_INFO, "end %f\n", ch->end * av_q2d(ch->time_base));
2998 
2999  dump_metadata(NULL, ch->metadata, " ");
3000  }
3001  if(ic->nb_programs) {
3002  int j, k, total = 0;
3003  for(j=0; j<ic->nb_programs; j++) {
3005  "name", NULL, 0);
3006  av_log(NULL, AV_LOG_INFO, " Program %d %s\n", ic->programs[j]->id,
3007  name ? name->value : "");
3008  dump_metadata(NULL, ic->programs[j]->metadata, " ");
3009  for(k=0; k<ic->programs[j]->nb_stream_indexes; k++) {
3010  dump_stream_format(ic, ic->programs[j]->stream_index[k], index, is_output);
3011  printed[ic->programs[j]->stream_index[k]] = 1;
3012  }
3013  total += ic->programs[j]->nb_stream_indexes;
3014  }
3015  if (total < ic->nb_streams)
3016  av_log(NULL, AV_LOG_INFO, " No Program\n");
3017  }
3018  for(i=0;i<ic->nb_streams;i++)
3019  if (!printed[i])
3020  dump_stream_format(ic, i, index, is_output);
3021 
3022  av_free(printed);
3023 }
3024 
3025 #if FF_API_AV_GETTIME && CONFIG_SHARED && HAVE_SYMVER
3026 FF_SYMVER(int64_t, av_gettime, (void), "LIBAVFORMAT_54")
3027 {
3028  return av_gettime();
3029 }
3030 #endif
3031 
3032 uint64_t ff_ntp_time(void)
3033 {
3034  return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US;
3035 }
3036 
3037 int av_get_frame_filename(char *buf, int buf_size,
3038  const char *path, int number)
3039 {
3040  const char *p;
3041  char *q, buf1[20], c;
3042  int nd, len, percentd_found;
3043 
3044  q = buf;
3045  p = path;
3046  percentd_found = 0;
3047  for(;;) {
3048  c = *p++;
3049  if (c == '\0')
3050  break;
3051  if (c == '%') {
3052  do {
3053  nd = 0;
3054  while (isdigit(*p)) {
3055  nd = nd * 10 + *p++ - '0';
3056  }
3057  c = *p++;
3058  } while (isdigit(c));
3059 
3060  switch(c) {
3061  case '%':
3062  goto addchar;
3063  case 'd':
3064  if (percentd_found)
3065  goto fail;
3066  percentd_found = 1;
3067  snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
3068  len = strlen(buf1);
3069  if ((q - buf + len) > buf_size - 1)
3070  goto fail;
3071  memcpy(q, buf1, len);
3072  q += len;
3073  break;
3074  default:
3075  goto fail;
3076  }
3077  } else {
3078  addchar:
3079  if ((q - buf) < buf_size - 1)
3080  *q++ = c;
3081  }
3082  }
3083  if (!percentd_found)
3084  goto fail;
3085  *q = '\0';
3086  return 0;
3087  fail:
3088  *q = '\0';
3089  return -1;
3090 }
3091 
3092 static void hex_dump_internal(void *avcl, FILE *f, int level,
3093  const uint8_t *buf, int size)
3094 {
3095  int len, i, j, c;
3096 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3097 
3098  for(i=0;i<size;i+=16) {
3099  len = size - i;
3100  if (len > 16)
3101  len = 16;
3102  PRINT("%08x ", i);
3103  for(j=0;j<16;j++) {
3104  if (j < len)
3105  PRINT(" %02x", buf[i+j]);
3106  else
3107  PRINT(" ");
3108  }
3109  PRINT(" ");
3110  for(j=0;j<len;j++) {
3111  c = buf[i+j];
3112  if (c < ' ' || c > '~')
3113  c = '.';
3114  PRINT("%c", c);
3115  }
3116  PRINT("\n");
3117  }
3118 #undef PRINT
3119 }
3120 
3121 void av_hex_dump(FILE *f, const uint8_t *buf, int size)
3122 {
3123  hex_dump_internal(NULL, f, 0, buf, size);
3124 }
3125 
3126 void av_hex_dump_log(void *avcl, int level, const uint8_t *buf, int size)
3127 {
3128  hex_dump_internal(avcl, NULL, level, buf, size);
3129 }
3130 
3131 static void pkt_dump_internal(void *avcl, FILE *f, int level, AVPacket *pkt, int dump_payload, AVRational time_base)
3132 {
3133 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3134  PRINT("stream #%d:\n", pkt->stream_index);
3135  PRINT(" keyframe=%d\n", ((pkt->flags & AV_PKT_FLAG_KEY) != 0));
3136  PRINT(" duration=%0.3f\n", pkt->duration * av_q2d(time_base));
3137  /* DTS is _always_ valid after av_read_frame() */
3138  PRINT(" dts=");
3139  if (pkt->dts == AV_NOPTS_VALUE)
3140  PRINT("N/A");
3141  else
3142  PRINT("%0.3f", pkt->dts * av_q2d(time_base));
3143  /* PTS may not be known if B-frames are present. */
3144  PRINT(" pts=");
3145  if (pkt->pts == AV_NOPTS_VALUE)
3146  PRINT("N/A");
3147  else
3148  PRINT("%0.3f", pkt->pts * av_q2d(time_base));
3149  PRINT("\n");
3150  PRINT(" size=%d\n", pkt->size);
3151 #undef PRINT
3152  if (dump_payload)
3153  av_hex_dump(f, pkt->data, pkt->size);
3154 }
3155 
3156 void av_pkt_dump2(FILE *f, AVPacket *pkt, int dump_payload, AVStream *st)
3157 {
3158  pkt_dump_internal(NULL, f, 0, pkt, dump_payload, st->time_base);
3159 }
3160 
3161 void av_pkt_dump_log2(void *avcl, int level, AVPacket *pkt, int dump_payload,
3162  AVStream *st)
3163 {
3164  pkt_dump_internal(avcl, NULL, level, pkt, dump_payload, st->time_base);
3165 }
3166 
3167 void av_url_split(char *proto, int proto_size,
3168  char *authorization, int authorization_size,
3169  char *hostname, int hostname_size,
3170  int *port_ptr,
3171  char *path, int path_size,
3172  const char *url)
3173 {
3174  const char *p, *ls, *at, *col, *brk;
3175 
3176  if (port_ptr) *port_ptr = -1;
3177  if (proto_size > 0) proto[0] = 0;
3178  if (authorization_size > 0) authorization[0] = 0;
3179  if (hostname_size > 0) hostname[0] = 0;
3180  if (path_size > 0) path[0] = 0;
3181 
3182  /* parse protocol */
3183  if ((p = strchr(url, ':'))) {
3184  av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
3185  p++; /* skip ':' */
3186  if (*p == '/') p++;
3187  if (*p == '/') p++;
3188  } else {
3189  /* no protocol means plain filename */
3190  av_strlcpy(path, url, path_size);
3191  return;
3192  }
3193 
3194  /* separate path from hostname */
3195  ls = strchr(p, '/');
3196  if(!ls)
3197  ls = strchr(p, '?');
3198  if(ls)
3199  av_strlcpy(path, ls, path_size);
3200  else
3201  ls = &p[strlen(p)]; // XXX
3202 
3203  /* the rest is hostname, use that to parse auth/port */
3204  if (ls != p) {
3205  /* authorization (user[:pass]@hostname) */
3206  if ((at = strchr(p, '@')) && at < ls) {
3207  av_strlcpy(authorization, p,
3208  FFMIN(authorization_size, at + 1 - p));
3209  p = at + 1; /* skip '@' */
3210  }
3211 
3212  if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
3213  /* [host]:port */
3214  av_strlcpy(hostname, p + 1,
3215  FFMIN(hostname_size, brk - p));
3216  if (brk[1] == ':' && port_ptr)
3217  *port_ptr = atoi(brk + 2);
3218  } else if ((col = strchr(p, ':')) && col < ls) {
3219  av_strlcpy(hostname, p,
3220  FFMIN(col + 1 - p, hostname_size));
3221  if (port_ptr) *port_ptr = atoi(col + 1);
3222  } else
3223  av_strlcpy(hostname, p,
3224  FFMIN(ls + 1 - p, hostname_size));
3225  }
3226 }
3227 
3228 char *ff_data_to_hex(char *buff, const uint8_t *src, int s, int lowercase)
3229 {
3230  int i;
3231  static const char hex_table_uc[16] = { '0', '1', '2', '3',
3232  '4', '5', '6', '7',
3233  '8', '9', 'A', 'B',
3234  'C', 'D', 'E', 'F' };
3235  static const char hex_table_lc[16] = { '0', '1', '2', '3',
3236  '4', '5', '6', '7',
3237  '8', '9', 'a', 'b',
3238  'c', 'd', 'e', 'f' };
3239  const char *hex_table = lowercase ? hex_table_lc : hex_table_uc;
3240 
3241  for(i = 0; i < s; i++) {
3242  buff[i * 2] = hex_table[src[i] >> 4];
3243  buff[i * 2 + 1] = hex_table[src[i] & 0xF];
3244  }
3245 
3246  return buff;
3247 }
3248 
3249 int ff_hex_to_data(uint8_t *data, const char *p)
3250 {
3251  int c, len, v;
3252 
3253  len = 0;
3254  v = 1;
3255  for (;;) {
3256  p += strspn(p, SPACE_CHARS);
3257  if (*p == '\0')
3258  break;
3259  c = toupper((unsigned char) *p++);
3260  if (c >= '0' && c <= '9')
3261  c = c - '0';
3262  else if (c >= 'A' && c <= 'F')
3263  c = c - 'A' + 10;
3264  else
3265  break;
3266  v = (v << 4) | c;
3267  if (v & 0x100) {
3268  if (data)
3269  data[len] = v;
3270  len++;
3271  v = 1;
3272  }
3273  }
3274  return len;
3275 }
3276 
3277 void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits,
3278  unsigned int pts_num, unsigned int pts_den)
3279 {
3280  AVRational new_tb;
3281  if(av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)){
3282  if(new_tb.num != pts_num)
3283  av_log(NULL, AV_LOG_DEBUG, "st:%d removing common factor %d from timebase\n", s->index, pts_num/new_tb.num);
3284  }else
3285  av_log(NULL, AV_LOG_WARNING, "st:%d has too large timebase, reducing\n", s->index);
3286 
3287  if(new_tb.num <= 0 || new_tb.den <= 0) {
3288  av_log(NULL, AV_LOG_ERROR, "Ignoring attempt to set invalid timebase for st:%d\n", s->index);
3289  return;
3290  }
3291  s->time_base = new_tb;
3292  s->pts_wrap_bits = pts_wrap_bits;
3293 }
3294 
3295 int ff_url_join(char *str, int size, const char *proto,
3296  const char *authorization, const char *hostname,
3297  int port, const char *fmt, ...)
3298 {
3299 #if CONFIG_NETWORK
3300  struct addrinfo hints = { 0 }, *ai;
3301 #endif
3302 
3303  str[0] = '\0';
3304  if (proto)
3305  av_strlcatf(str, size, "%s://", proto);
3306  if (authorization && authorization[0])
3307  av_strlcatf(str, size, "%s@", authorization);
3308 #if CONFIG_NETWORK && defined(AF_INET6)
3309  /* Determine if hostname is a numerical IPv6 address,
3310  * properly escape it within [] in that case. */
3311  hints.ai_flags = AI_NUMERICHOST;
3312  if (!getaddrinfo(hostname, NULL, &hints, &ai)) {
3313  if (ai->ai_family == AF_INET6) {
3314  av_strlcat(str, "[", size);
3315  av_strlcat(str, hostname, size);
3316  av_strlcat(str, "]", size);
3317  } else {
3318  av_strlcat(str, hostname, size);
3319  }
3320  freeaddrinfo(ai);
3321  } else
3322 #endif
3323  /* Not an IPv6 address, just output the plain string. */
3324  av_strlcat(str, hostname, size);
3325 
3326  if (port >= 0)
3327  av_strlcatf(str, size, ":%d", port);
3328  if (fmt) {
3329  va_list vl;
3330  int len = strlen(str);
3331 
3332  va_start(vl, fmt);
3333  vsnprintf(str + len, size > len ? size - len : 0, fmt, vl);
3334  va_end(vl);
3335  }
3336  return strlen(str);
3337 }
3338 
3339 int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
3340  AVFormatContext *src)
3341 {
3342  AVPacket local_pkt;
3343 
3344  local_pkt = *pkt;
3345  local_pkt.stream_index = dst_stream;
3346  if (pkt->pts != AV_NOPTS_VALUE)
3347  local_pkt.pts = av_rescale_q(pkt->pts,
3348  src->streams[pkt->stream_index]->time_base,
3349  dst->streams[dst_stream]->time_base);
3350  if (pkt->dts != AV_NOPTS_VALUE)
3351  local_pkt.dts = av_rescale_q(pkt->dts,
3352  src->streams[pkt->stream_index]->time_base,
3353  dst->streams[dst_stream]->time_base);
3354  return av_write_frame(dst, &local_pkt);
3355 }
3356 
3357 void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf,
3358  void *context)
3359 {
3360  const char *ptr = str;
3361 
3362  /* Parse key=value pairs. */
3363  for (;;) {
3364  const char *key;
3365  char *dest = NULL, *dest_end;
3366  int key_len, dest_len = 0;
3367 
3368  /* Skip whitespace and potential commas. */
3369  while (*ptr && (isspace(*ptr) || *ptr == ','))
3370  ptr++;
3371  if (!*ptr)
3372  break;
3373 
3374  key = ptr;
3375 
3376  if (!(ptr = strchr(key, '=')))
3377  break;
3378  ptr++;
3379  key_len = ptr - key;
3380 
3381  callback_get_buf(context, key, key_len, &dest, &dest_len);
3382  dest_end = dest + dest_len - 1;
3383 
3384  if (*ptr == '\"') {
3385  ptr++;
3386  while (*ptr && *ptr != '\"') {
3387  if (*ptr == '\\') {
3388  if (!ptr[1])
3389  break;
3390  if (dest && dest < dest_end)
3391  *dest++ = ptr[1];
3392  ptr += 2;
3393  } else {
3394  if (dest && dest < dest_end)
3395  *dest++ = *ptr;
3396  ptr++;
3397  }
3398  }
3399  if (*ptr == '\"')
3400  ptr++;
3401  } else {
3402  for (; *ptr && !(isspace(*ptr) || *ptr == ','); ptr++)
3403  if (dest && dest < dest_end)
3404  *dest++ = *ptr;
3405  }
3406  if (dest)
3407  *dest = 0;
3408  }
3409 }
3410 
3412 {
3413  int i;
3414  for (i = 0; i < s->nb_streams; i++) {
3415  if (s->streams[i]->id == id)
3416  return i;
3417  }
3418  return -1;
3419 }
3420 
3421 void ff_make_absolute_url(char *buf, int size, const char *base,
3422  const char *rel)
3423 {
3424  char *sep, *path_query;
3425  /* Absolute path, relative to the current server */
3426  if (base && strstr(base, "://") && rel[0] == '/') {
3427  if (base != buf)
3428  av_strlcpy(buf, base, size);
3429  sep = strstr(buf, "://");
3430  if (sep) {
3431  /* Take scheme from base url */
3432  if (rel[1] == '/') {
3433  sep[1] = '\0';
3434  } else {
3435  /* Take scheme and host from base url */
3436  sep += 3;
3437  sep = strchr(sep, '/');
3438  if (sep)
3439  *sep = '\0';
3440  }
3441  }
3442  av_strlcat(buf, rel, size);
3443  return;
3444  }
3445  /* If rel actually is an absolute url, just copy it */
3446  if (!base || strstr(rel, "://") || rel[0] == '/') {
3447  av_strlcpy(buf, rel, size);
3448  return;
3449  }
3450  if (base != buf)
3451  av_strlcpy(buf, base, size);
3452 
3453  /* Strip off any query string from base */
3454  path_query = strchr(buf, '?');
3455  if (path_query != NULL)
3456  *path_query = '\0';
3457 
3458  /* Is relative path just a new query part? */
3459  if (rel[0] == '?') {
3460  av_strlcat(buf, rel, size);
3461  return;
3462  }
3463 
3464  /* Remove the file name from the base url */
3465  sep = strrchr(buf, '/');
3466  if (sep)
3467  sep[1] = '\0';
3468  else
3469  buf[0] = '\0';
3470  while (av_strstart(rel, "../", NULL) && sep) {
3471  /* Remove the path delimiter at the end */
3472  sep[0] = '\0';
3473  sep = strrchr(buf, '/');
3474  /* If the next directory name to pop off is "..", break here */
3475  if (!strcmp(sep ? &sep[1] : buf, "..")) {
3476  /* Readd the slash we just removed */
3477  av_strlcat(buf, "/", size);
3478  break;
3479  }
3480  /* Cut off the directory name */
3481  if (sep)
3482  sep[1] = '\0';
3483  else
3484  buf[0] = '\0';
3485  rel += 3;
3486  }
3487  av_strlcat(buf, rel, size);
3488 }
3489 
3490 int64_t ff_iso8601_to_unix_time(const char *datestr)
3491 {
3492 #if HAVE_STRPTIME
3493  struct tm time1 = {0}, time2 = {0};
3494  char *ret1, *ret2;
3495  ret1 = strptime(datestr, "%Y - %m - %d %T", &time1);
3496  ret2 = strptime(datestr, "%Y - %m - %dT%T", &time2);
3497  if (ret2 && !ret1)
3498  return av_timegm(&time2);
3499  else
3500  return av_timegm(&time1);
3501 #else
3502  av_log(NULL, AV_LOG_WARNING, "strptime() unavailable on this system, cannot convert "
3503  "the date string.\n");
3504  return 0;
3505 #endif
3506 }
3507 
3508 int avformat_query_codec(AVOutputFormat *ofmt, enum AVCodecID codec_id, int std_compliance)
3509 {
3510  if (ofmt) {
3511  if (ofmt->query_codec)
3512  return ofmt->query_codec(codec_id, std_compliance);
3513  else if (ofmt->codec_tag)
3514  return !!av_codec_get_tag(ofmt->codec_tag, codec_id);
3515  else if (codec_id == ofmt->video_codec || codec_id == ofmt->audio_codec ||
3516  codec_id == ofmt->subtitle_codec)
3517  return 1;
3518  }
3519  return AVERROR_PATCHWELCOME;
3520 }
3521 
3523 {
3524 #if CONFIG_NETWORK
3525  int ret;
3527  if ((ret = ff_network_init()) < 0)
3528  return ret;
3529  ff_tls_init();
3530 #endif
3531  return 0;
3532 }
3533 
3535 {
3536 #if CONFIG_NETWORK
3537  ff_network_close();
3538  ff_tls_deinit();
3539 #endif
3540  return 0;
3541 }
3542 
3544  uint64_t channel_layout, int32_t sample_rate,
3546 {
3547  uint32_t flags = 0;
3548  int size = 4;
3549  uint8_t *data;
3550  if (!pkt)
3551  return AVERROR(EINVAL);
3552  if (channels) {
3553  size += 4;
3555  }
3556  if (channel_layout) {
3557  size += 8;
3559  }
3560  if (sample_rate) {
3561  size += 4;
3563  }
3564  if (width || height) {
3565  size += 8;
3567  }
3569  if (!data)
3570  return AVERROR(ENOMEM);
3571  bytestream_put_le32(&data, flags);
3572  if (channels)
3573  bytestream_put_le32(&data, channels);
3574  if (channel_layout)
3575  bytestream_put_le64(&data, channel_layout);
3576  if (sample_rate)
3577  bytestream_put_le32(&data, sample_rate);
3578  if (width || height) {
3579  bytestream_put_le32(&data, width);
3580  bytestream_put_le32(&data, height);
3581  }
3582  return 0;
3583 }
3584 
3586 {
3587  return ff_codec_bmp_tags;
3588 }
3590 {
3591  return ff_codec_wav_tags;
3592 }