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 "riff.h"
39 #include "audiointerleave.h"
40 #include "url.h"
41 #include <sys/time.h>
42 #include <time.h>
43 #include <stdarg.h>
44 #if CONFIG_NETWORK
45 #include "network.h"
46 #endif
47 
48 #undef NDEBUG
49 #include <assert.h>
50 
56 unsigned avformat_version(void)
57 {
59 }
60 
61 const char *avformat_configuration(void)
62 {
63  return LIBAV_CONFIGURATION;
64 }
65 
66 const char *avformat_license(void)
67 {
68 #define LICENSE_PREFIX "libavformat license: "
69  return LICENSE_PREFIX LIBAV_LICENSE + sizeof(LICENSE_PREFIX) - 1;
70 }
71 
72 /* fraction handling */
73 
84 static void frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
85 {
86  num += (den >> 1);
87  if (num >= den) {
88  val += num / den;
89  num = num % den;
90  }
91  f->val = val;
92  f->num = num;
93  f->den = den;
94 }
95 
102 static void frac_add(AVFrac *f, int64_t incr)
103 {
104  int64_t num, den;
105 
106  num = f->num + incr;
107  den = f->den;
108  if (num < 0) {
109  f->val += num / den;
110  num = num % den;
111  if (num < 0) {
112  num += den;
113  f->val--;
114  }
115  } else if (num >= den) {
116  f->val += num / den;
117  num = num % den;
118  }
119  f->num = num;
120 }
121 
126 
128 {
129  if(f) return f->next;
130  else return first_iformat;
131 }
132 
134 {
135  if(f) return f->next;
136  else return first_oformat;
137 }
138 
140 {
141  AVInputFormat **p;
142  p = &first_iformat;
143  while (*p != NULL) p = &(*p)->next;
144  *p = format;
145  format->next = NULL;
146 }
147 
149 {
150  AVOutputFormat **p;
151  p = &first_oformat;
152  while (*p != NULL) p = &(*p)->next;
153  *p = format;
154  format->next = NULL;
155 }
156 
157 int av_match_ext(const char *filename, const char *extensions)
158 {
159  const char *ext, *p;
160  char ext1[32], *q;
161 
162  if(!filename)
163  return 0;
164 
165  ext = strrchr(filename, '.');
166  if (ext) {
167  ext++;
168  p = extensions;
169  for(;;) {
170  q = ext1;
171  while (*p != '\0' && *p != ',' && q-ext1<sizeof(ext1)-1)
172  *q++ = *p++;
173  *q = '\0';
174  if (!av_strcasecmp(ext1, ext))
175  return 1;
176  if (*p == '\0')
177  break;
178  p++;
179  }
180  }
181  return 0;
182 }
183 
184 static int match_format(const char *name, const char *names)
185 {
186  const char *p;
187  int len, namelen;
188 
189  if (!name || !names)
190  return 0;
191 
192  namelen = strlen(name);
193  while ((p = strchr(names, ','))) {
194  len = FFMAX(p - names, namelen);
195  if (!av_strncasecmp(name, names, len))
196  return 1;
197  names = p+1;
198  }
199  return !av_strcasecmp(name, names);
200 }
201 
202 AVOutputFormat *av_guess_format(const char *short_name, const char *filename,
203  const char *mime_type)
204 {
205  AVOutputFormat *fmt = NULL, *fmt_found;
206  int score_max, score;
207 
208  /* specific test for image sequences */
209 #if CONFIG_IMAGE2_MUXER
210  if (!short_name && filename &&
211  av_filename_number_test(filename) &&
212  ff_guess_image2_codec(filename) != CODEC_ID_NONE) {
213  return av_guess_format("image2", NULL, NULL);
214  }
215 #endif
216  /* Find the proper file type. */
217  fmt_found = NULL;
218  score_max = 0;
219  while ((fmt = av_oformat_next(fmt))) {
220  score = 0;
221  if (fmt->name && short_name && !strcmp(fmt->name, short_name))
222  score += 100;
223  if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
224  score += 10;
225  if (filename && fmt->extensions &&
226  av_match_ext(filename, fmt->extensions)) {
227  score += 5;
228  }
229  if (score > score_max) {
230  score_max = score;
231  fmt_found = fmt;
232  }
233  }
234  return fmt_found;
235 }
236 
237 enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
238  const char *filename, const char *mime_type, enum AVMediaType type){
239  if(type == AVMEDIA_TYPE_VIDEO){
241 
242 #if CONFIG_IMAGE2_MUXER
243  if(!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")){
244  codec_id= ff_guess_image2_codec(filename);
245  }
246 #endif
247  if(codec_id == CODEC_ID_NONE)
248  codec_id= fmt->video_codec;
249  return codec_id;
250  }else if(type == AVMEDIA_TYPE_AUDIO)
251  return fmt->audio_codec;
252  else if (type == AVMEDIA_TYPE_SUBTITLE)
253  return fmt->subtitle_codec;
254  else
255  return CODEC_ID_NONE;
256 }
257 
258 AVInputFormat *av_find_input_format(const char *short_name)
259 {
260  AVInputFormat *fmt = NULL;
261  while ((fmt = av_iformat_next(fmt))) {
262  if (match_format(short_name, fmt->name))
263  return fmt;
264  }
265  return NULL;
266 }
267 
268 
270 {
271  int ret= av_new_packet(pkt, size);
272 
273  if(ret<0)
274  return ret;
275 
276  pkt->pos= avio_tell(s);
277 
278  ret= avio_read(s, pkt->data, size);
279  if(ret<=0)
280  av_free_packet(pkt);
281  else
282  av_shrink_packet(pkt, ret);
283 
284  return ret;
285 }
286 
288 {
289  int ret;
290  int old_size;
291  if (!pkt->size)
292  return av_get_packet(s, pkt, size);
293  old_size = pkt->size;
294  ret = av_grow_packet(pkt, size);
295  if (ret < 0)
296  return ret;
297  ret = avio_read(s, pkt->data + old_size, size);
298  av_shrink_packet(pkt, old_size + FFMAX(ret, 0));
299  return ret;
300 }
301 
302 
303 int av_filename_number_test(const char *filename)
304 {
305  char buf[1024];
306  return filename && (av_get_frame_filename(buf, sizeof(buf), filename, 1)>=0);
307 }
308 
309 AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
310 {
311  AVProbeData lpd = *pd;
312  AVInputFormat *fmt1 = NULL, *fmt;
313  int score, id3 = 0;
314 
315  if (lpd.buf_size > 10 && ff_id3v2_match(lpd.buf, ID3v2_DEFAULT_MAGIC)) {
316  int id3len = ff_id3v2_tag_len(lpd.buf);
317  if (lpd.buf_size > id3len + 16) {
318  lpd.buf += id3len;
319  lpd.buf_size -= id3len;
320  }
321  id3 = 1;
322  }
323 
324  fmt = NULL;
325  while ((fmt1 = av_iformat_next(fmt1))) {
326  if (!is_opened == !(fmt1->flags & AVFMT_NOFILE))
327  continue;
328  score = 0;
329  if (fmt1->read_probe) {
330  score = fmt1->read_probe(&lpd);
331  } else if (fmt1->extensions) {
332  if (av_match_ext(lpd.filename, fmt1->extensions)) {
333  score = 50;
334  }
335  }
336  if (score > *score_max) {
337  *score_max = score;
338  fmt = fmt1;
339  }else if (score == *score_max)
340  fmt = NULL;
341  }
342 
343  /* a hack for files with huge id3v2 tags -- try to guess by file extension. */
344  if (!fmt && is_opened && *score_max < AVPROBE_SCORE_MAX/4) {
345  while ((fmt = av_iformat_next(fmt)))
346  if (fmt->extensions && av_match_ext(lpd.filename, fmt->extensions)) {
347  *score_max = AVPROBE_SCORE_MAX/4;
348  break;
349  }
350  }
351 
352  if (!fmt && id3 && *score_max < AVPROBE_SCORE_MAX/4-1) {
353  while ((fmt = av_iformat_next(fmt)))
354  if (fmt->extensions && av_match_ext("mp3", fmt->extensions)) {
355  *score_max = AVPROBE_SCORE_MAX/4-1;
356  break;
357  }
358  }
359 
360  return fmt;
361 }
362 
364  int score=0;
365  return av_probe_input_format2(pd, is_opened, &score);
366 }
367 
369 {
370  static const struct {
371  const char *name; enum CodecID id; enum AVMediaType type;
372  } fmt_id_type[] = {
373  { "aac" , CODEC_ID_AAC , AVMEDIA_TYPE_AUDIO },
374  { "ac3" , CODEC_ID_AC3 , AVMEDIA_TYPE_AUDIO },
375  { "dts" , CODEC_ID_DTS , AVMEDIA_TYPE_AUDIO },
376  { "eac3" , CODEC_ID_EAC3 , AVMEDIA_TYPE_AUDIO },
377  { "h264" , CODEC_ID_H264 , AVMEDIA_TYPE_VIDEO },
378  { "m4v" , CODEC_ID_MPEG4 , AVMEDIA_TYPE_VIDEO },
379  { "mp3" , CODEC_ID_MP3 , AVMEDIA_TYPE_AUDIO },
380  { "mpegvideo", CODEC_ID_MPEG2VIDEO, AVMEDIA_TYPE_VIDEO },
381  { 0 }
382  };
383  AVInputFormat *fmt = av_probe_input_format2(pd, 1, &score);
384 
385  if (fmt) {
386  int i;
387  av_log(s, AV_LOG_DEBUG, "Probe with size=%d, packets=%d detected %s with score=%d\n",
388  pd->buf_size, MAX_PROBE_PACKETS - st->probe_packets, fmt->name, score);
389  for (i = 0; fmt_id_type[i].name; i++) {
390  if (!strcmp(fmt->name, fmt_id_type[i].name)) {
391  st->codec->codec_id = fmt_id_type[i].id;
392  st->codec->codec_type = fmt_id_type[i].type;
393  break;
394  }
395  }
396  }
397  return !!fmt;
398 }
399 
400 /************************************************************/
401 /* input media file */
402 
403 #if FF_API_FORMAT_PARAMETERS
404 static AVDictionary *convert_format_parameters(AVFormatParameters *ap)
405 {
406  char buf[1024];
407  AVDictionary *opts = NULL;
408 
409  if (!ap)
410  return NULL;
411 
412  if (ap->time_base.num) {
413  snprintf(buf, sizeof(buf), "%d/%d", ap->time_base.den, ap->time_base.num);
414  av_dict_set(&opts, "framerate", buf, 0);
415  }
416  if (ap->sample_rate) {
417  snprintf(buf, sizeof(buf), "%d", ap->sample_rate);
418  av_dict_set(&opts, "sample_rate", buf, 0);
419  }
420  if (ap->channels) {
421  snprintf(buf, sizeof(buf), "%d", ap->channels);
422  av_dict_set(&opts, "channels", buf, 0);
423  }
424  if (ap->width || ap->height) {
425  snprintf(buf, sizeof(buf), "%dx%d", ap->width, ap->height);
426  av_dict_set(&opts, "video_size", buf, 0);
427  }
428  if (ap->pix_fmt != PIX_FMT_NONE) {
429  av_dict_set(&opts, "pixel_format", av_get_pix_fmt_name(ap->pix_fmt), 0);
430  }
431  if (ap->channel) {
432  snprintf(buf, sizeof(buf), "%d", ap->channel);
433  av_dict_set(&opts, "channel", buf, 0);
434  }
435  if (ap->standard) {
436  av_dict_set(&opts, "standard", ap->standard, 0);
437  }
438  if (ap->mpeg2ts_compute_pcr) {
439  av_dict_set(&opts, "mpeg2ts_compute_pcr", "1", 0);
440  }
441  if (ap->initial_pause) {
442  av_dict_set(&opts, "initial_pause", "1", 0);
443  }
444  return opts;
445 }
446 
450 int av_open_input_stream(AVFormatContext **ic_ptr,
451  AVIOContext *pb, const char *filename,
453 {
454  int err;
455  AVDictionary *opts;
456  AVFormatContext *ic;
457  AVFormatParameters default_ap;
458 
459  if(!ap){
460  ap=&default_ap;
461  memset(ap, 0, sizeof(default_ap));
462  }
463  opts = convert_format_parameters(ap);
464 
465  if(!ap->prealloced_context)
466  ic = avformat_alloc_context();
467  else
468  ic = *ic_ptr;
469  if (!ic) {
470  err = AVERROR(ENOMEM);
471  goto fail;
472  }
473  if (pb && fmt && fmt->flags & AVFMT_NOFILE)
474  av_log(ic, AV_LOG_WARNING, "Custom AVIOContext makes no sense and "
475  "will be ignored with AVFMT_NOFILE format.\n");
476  else
477  ic->pb = pb;
478 
479  if ((err = avformat_open_input(&ic, filename, fmt, &opts)) < 0)
480  goto fail;
481  ic->pb = ic->pb ? ic->pb : pb; // don't leak custom pb if it wasn't set above
482 
483 fail:
484  *ic_ptr = ic;
485  av_dict_free(&opts);
486  return err;
487 }
488 #endif
489 
491 #define PROBE_BUF_MIN 2048
492 #define PROBE_BUF_MAX (1<<20)
493 
495  const char *filename, void *logctx,
496  unsigned int offset, unsigned int max_probe_size)
497 {
498  AVProbeData pd = { filename ? filename : "", NULL, -offset };
499  unsigned char *buf = NULL;
500  int ret = 0, probe_size;
501 
502  if (!max_probe_size) {
503  max_probe_size = PROBE_BUF_MAX;
504  } else if (max_probe_size > PROBE_BUF_MAX) {
505  max_probe_size = PROBE_BUF_MAX;
506  } else if (max_probe_size < PROBE_BUF_MIN) {
507  return AVERROR(EINVAL);
508  }
509 
510  if (offset >= max_probe_size) {
511  return AVERROR(EINVAL);
512  }
513 
514  for(probe_size= PROBE_BUF_MIN; probe_size<=max_probe_size && !*fmt;
515  probe_size = FFMIN(probe_size<<1, FFMAX(max_probe_size, probe_size+1))) {
516  int score = probe_size < max_probe_size ? AVPROBE_SCORE_MAX/4 : 0;
517 
518  if (probe_size < offset) {
519  continue;
520  }
521 
522  /* read probe data */
523  buf = av_realloc(buf, probe_size + AVPROBE_PADDING_SIZE);
524  if ((ret = avio_read(pb, buf + pd.buf_size, probe_size - pd.buf_size)) < 0) {
525  /* fail if error was not end of file, otherwise, lower score */
526  if (ret != AVERROR_EOF) {
527  av_free(buf);
528  return ret;
529  }
530  score = 0;
531  ret = 0; /* error was end of file, nothing read */
532  }
533  pd.buf_size += ret;
534  pd.buf = &buf[offset];
535 
536  memset(pd.buf + pd.buf_size, 0, AVPROBE_PADDING_SIZE);
537 
538  /* guess file format */
539  *fmt = av_probe_input_format2(&pd, 1, &score);
540  if(*fmt){
541  if(score <= AVPROBE_SCORE_MAX/4){ //this can only be true in the last iteration
542  av_log(logctx, AV_LOG_WARNING, "Format detected only with low score of %d, misdetection possible!\n", score);
543  }else
544  av_log(logctx, AV_LOG_DEBUG, "Probed with size=%d and score=%d\n", probe_size, score);
545  }
546  }
547 
548  if (!*fmt) {
549  av_free(buf);
550  return AVERROR_INVALIDDATA;
551  }
552 
553  /* rewind. reuse probe buffer to avoid seeking */
554  if ((ret = ffio_rewind_with_probe_data(pb, buf, pd.buf_size)) < 0)
555  av_free(buf);
556 
557  return ret;
558 }
559 
560 #if FF_API_FORMAT_PARAMETERS
561 int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
562  AVInputFormat *fmt,
563  int buf_size,
564  AVFormatParameters *ap)
565 {
566  int err;
567  AVDictionary *opts = convert_format_parameters(ap);
568 
569  if (!ap || !ap->prealloced_context)
570  *ic_ptr = NULL;
571 
572  err = avformat_open_input(ic_ptr, filename, fmt, &opts);
573 
574  av_dict_free(&opts);
575  return err;
576 }
577 #endif
578 
579 /* open input file and probe the format if necessary */
580 static int init_input(AVFormatContext *s, const char *filename, AVDictionary **options)
581 {
582  int ret;
583  AVProbeData pd = {filename, NULL, 0};
584 
585  if (s->pb) {
587  if (!s->iformat)
588  return av_probe_input_buffer(s->pb, &s->iformat, filename, s, 0, 0);
589  else if (s->iformat->flags & AVFMT_NOFILE)
590  return AVERROR(EINVAL);
591  return 0;
592  }
593 
594  if ( (s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
595  (!s->iformat && (s->iformat = av_probe_input_format(&pd, 0))))
596  return 0;
597 
598  if ((ret = avio_open2(&s->pb, filename, AVIO_FLAG_READ,
599  &s->interrupt_callback, options)) < 0)
600  return ret;
601  if (s->iformat)
602  return 0;
603  return av_probe_input_buffer(s->pb, &s->iformat, filename, s, 0, 0);
604 }
605 
606 int avformat_open_input(AVFormatContext **ps, const char *filename, AVInputFormat *fmt, AVDictionary **options)
607 {
608  AVFormatContext *s = *ps;
609  int ret = 0;
610  AVFormatParameters ap = { { 0 } };
611  AVDictionary *tmp = NULL;
612 
613  if (!s && !(s = avformat_alloc_context()))
614  return AVERROR(ENOMEM);
615  if (fmt)
616  s->iformat = fmt;
617 
618  if (options)
619  av_dict_copy(&tmp, *options, 0);
620 
621  if ((ret = av_opt_set_dict(s, &tmp)) < 0)
622  goto fail;
623 
624  if ((ret = init_input(s, filename, &tmp)) < 0)
625  goto fail;
626 
627  /* check filename in case an image number is expected */
628  if (s->iformat->flags & AVFMT_NEEDNUMBER) {
629  if (!av_filename_number_test(filename)) {
630  ret = AVERROR(EINVAL);
631  goto fail;
632  }
633  }
634 
636  av_strlcpy(s->filename, filename ? filename : "", sizeof(s->filename));
637 
638  /* allocate private data */
639  if (s->iformat->priv_data_size > 0) {
640  if (!(s->priv_data = av_mallocz(s->iformat->priv_data_size))) {
641  ret = AVERROR(ENOMEM);
642  goto fail;
643  }
644  if (s->iformat->priv_class) {
645  *(const AVClass**)s->priv_data = s->iformat->priv_class;
647  if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
648  goto fail;
649  }
650  }
651 
652  /* e.g. AVFMT_NOFILE formats will not have a AVIOContext */
653  if (s->pb)
655 
656  if (s->iformat->read_header)
657  if ((ret = s->iformat->read_header(s, &ap)) < 0)
658  goto fail;
659 
660  if (s->pb && !s->data_offset)
661  s->data_offset = avio_tell(s->pb);
662 
664 
665  if (options) {
666  av_dict_free(options);
667  *options = tmp;
668  }
669  *ps = s;
670  return 0;
671 
672 fail:
673  av_dict_free(&tmp);
674  if (s->pb && !(s->flags & AVFMT_FLAG_CUSTOM_IO))
675  avio_close(s->pb);
677  *ps = NULL;
678  return ret;
679 }
680 
681 /*******************************************************/
682 
683 static AVPacket *add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt,
684  AVPacketList **plast_pktl){
685  AVPacketList *pktl = av_mallocz(sizeof(AVPacketList));
686  if (!pktl)
687  return NULL;
688 
689  if (*packet_buffer)
690  (*plast_pktl)->next = pktl;
691  else
692  *packet_buffer = pktl;
693 
694  /* add the packet in the buffered packet list */
695  *plast_pktl = pktl;
696  pktl->pkt= *pkt;
697  return &pktl->pkt;
698 }
699 
701 {
702  int ret, i;
703  AVStream *st;
704 
705  for(;;){
706  AVPacketList *pktl = s->raw_packet_buffer;
707 
708  if (pktl) {
709  *pkt = pktl->pkt;
710  if(s->streams[pkt->stream_index]->codec->codec_id != CODEC_ID_PROBE ||
711  !s->streams[pkt->stream_index]->probe_packets ||
713  AVProbeData *pd = &s->streams[pkt->stream_index]->probe_data;
714  av_freep(&pd->buf);
715  pd->buf_size = 0;
716  s->raw_packet_buffer = pktl->next;
718  av_free(pktl);
719  return 0;
720  }
721  }
722 
723  av_init_packet(pkt);
724  ret= s->iformat->read_packet(s, pkt);
725  if (ret < 0) {
726  if (!pktl || ret == AVERROR(EAGAIN))
727  return ret;
728  for (i = 0; i < s->nb_streams; i++)
729  s->streams[i]->probe_packets = 0;
730  continue;
731  }
732 
733  if ((s->flags & AVFMT_FLAG_DISCARD_CORRUPT) &&
734  (pkt->flags & AV_PKT_FLAG_CORRUPT)) {
736  "Dropped corrupted packet (stream = %d)\n",
737  pkt->stream_index);
738  av_free_packet(pkt);
739  continue;
740  }
741 
742  st= s->streams[pkt->stream_index];
743 
744  switch(st->codec->codec_type){
745  case AVMEDIA_TYPE_VIDEO:
747  break;
748  case AVMEDIA_TYPE_AUDIO:
750  break;
753  break;
754  }
755 
756  if(!pktl && (st->codec->codec_id != CODEC_ID_PROBE ||
757  !st->probe_packets))
758  return ret;
759 
762 
763  if(st->codec->codec_id == CODEC_ID_PROBE){
764  AVProbeData *pd = &st->probe_data;
765  av_log(s, AV_LOG_DEBUG, "probing stream %d\n", st->index);
766  --st->probe_packets;
767 
768  pd->buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
769  memcpy(pd->buf+pd->buf_size, pkt->data, pkt->size);
770  pd->buf_size += pkt->size;
771  memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);
772 
773  if(av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)){
774  //FIXME we do not reduce score to 0 for the case of running out of buffer space in bytes
775  set_codec_from_probe_data(s, st, pd, st->probe_packets > 0 ? AVPROBE_SCORE_MAX/4 : 0);
776  if(st->codec->codec_id != CODEC_ID_PROBE){
777  pd->buf_size=0;
778  av_freep(&pd->buf);
779  av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
780  }
781  }
782  }
783  }
784 }
785 
786 /**********************************************************/
787 
792 {
793  int frame_size;
794 
795  if(enc->codec_id == CODEC_ID_VORBIS)
796  return -1;
797 
798  if (enc->frame_size <= 1) {
799  int bits_per_sample = av_get_bits_per_sample(enc->codec_id);
800 
801  if (bits_per_sample) {
802  if (enc->channels == 0)
803  return -1;
804  frame_size = (size << 3) / (bits_per_sample * enc->channels);
805  } else {
806  /* used for example by ADPCM codecs */
807  if (enc->bit_rate == 0)
808  return -1;
809  frame_size = ((int64_t)size * 8 * enc->sample_rate) / enc->bit_rate;
810  }
811  } else {
812  frame_size = enc->frame_size;
813  }
814  return frame_size;
815 }
816 
817 
821 static void compute_frame_duration(int *pnum, int *pden, AVStream *st,
822  AVCodecParserContext *pc, AVPacket *pkt)
823 {
824  int frame_size;
825 
826  *pnum = 0;
827  *pden = 0;
828  switch(st->codec->codec_type) {
829  case AVMEDIA_TYPE_VIDEO:
830  if (st->r_frame_rate.num) {
831  *pnum = st->r_frame_rate.den;
832  *pden = st->r_frame_rate.num;
833  } else if(st->time_base.num*1000LL > st->time_base.den) {
834  *pnum = st->time_base.num;
835  *pden = st->time_base.den;
836  }else if(st->codec->time_base.num*1000LL > st->codec->time_base.den){
837  *pnum = st->codec->time_base.num;
838  *pden = st->codec->time_base.den;
839  if (pc && pc->repeat_pict) {
840  if (*pnum > INT_MAX / (1 + pc->repeat_pict))
841  *pden /= 1 + pc->repeat_pict;
842  else
843  *pnum *= 1 + pc->repeat_pict;
844  }
845  //If this codec can be interlaced or progressive then we need a parser to compute duration of a packet
846  //Thus if we have no parser in such case leave duration undefined.
847  if(st->codec->ticks_per_frame>1 && !pc){
848  *pnum = *pden = 0;
849  }
850  }
851  break;
852  case AVMEDIA_TYPE_AUDIO:
853  frame_size = get_audio_frame_size(st->codec, pkt->size);
854  if (frame_size <= 0 || st->codec->sample_rate <= 0)
855  break;
856  *pnum = frame_size;
857  *pden = st->codec->sample_rate;
858  break;
859  default:
860  break;
861  }
862 }
863 
864 static int is_intra_only(AVCodecContext *enc){
865  if(enc->codec_type == AVMEDIA_TYPE_AUDIO){
866  return 1;
867  }else if(enc->codec_type == AVMEDIA_TYPE_VIDEO){
868  switch(enc->codec_id){
869  case CODEC_ID_MJPEG:
870  case CODEC_ID_MJPEGB:
871  case CODEC_ID_LJPEG:
872  case CODEC_ID_PRORES:
873  case CODEC_ID_RAWVIDEO:
874  case CODEC_ID_DVVIDEO:
875  case CODEC_ID_HUFFYUV:
876  case CODEC_ID_FFVHUFF:
877  case CODEC_ID_ASV1:
878  case CODEC_ID_ASV2:
879  case CODEC_ID_VCR1:
880  case CODEC_ID_DNXHD:
881  case CODEC_ID_JPEG2000:
882  return 1;
883  default: break;
884  }
885  }
886  return 0;
887 }
888 
889 static void update_initial_timestamps(AVFormatContext *s, int stream_index,
890  int64_t dts, int64_t pts)
891 {
892  AVStream *st= s->streams[stream_index];
893  AVPacketList *pktl= s->packet_buffer;
894 
895  if(st->first_dts != AV_NOPTS_VALUE || dts == AV_NOPTS_VALUE || st->cur_dts == AV_NOPTS_VALUE)
896  return;
897 
898  st->first_dts= dts - st->cur_dts;
899  st->cur_dts= dts;
900 
901  for(; pktl; pktl= pktl->next){
902  if(pktl->pkt.stream_index != stream_index)
903  continue;
904  //FIXME think more about this check
905  if(pktl->pkt.pts != AV_NOPTS_VALUE && pktl->pkt.pts == pktl->pkt.dts)
906  pktl->pkt.pts += st->first_dts;
907 
908  if(pktl->pkt.dts != AV_NOPTS_VALUE)
909  pktl->pkt.dts += st->first_dts;
910 
911  if(st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
912  st->start_time= pktl->pkt.pts;
913  }
914  if (st->start_time == AV_NOPTS_VALUE)
915  st->start_time = pts;
916 }
917 
919 {
920  AVPacketList *pktl= s->packet_buffer;
921  int64_t cur_dts= 0;
922 
923  if(st->first_dts != AV_NOPTS_VALUE){
924  cur_dts= st->first_dts;
925  for(; pktl; pktl= pktl->next){
926  if(pktl->pkt.stream_index == pkt->stream_index){
927  if(pktl->pkt.pts != pktl->pkt.dts || pktl->pkt.dts != AV_NOPTS_VALUE || pktl->pkt.duration)
928  break;
929  cur_dts -= pkt->duration;
930  }
931  }
932  pktl= s->packet_buffer;
933  st->first_dts = cur_dts;
934  }else if(st->cur_dts)
935  return;
936 
937  for(; pktl; pktl= pktl->next){
938  if(pktl->pkt.stream_index != pkt->stream_index)
939  continue;
940  if(pktl->pkt.pts == pktl->pkt.dts && pktl->pkt.dts == AV_NOPTS_VALUE
941  && !pktl->pkt.duration){
942  pktl->pkt.dts= cur_dts;
943  if(!st->codec->has_b_frames)
944  pktl->pkt.pts= cur_dts;
945  cur_dts += pkt->duration;
946  pktl->pkt.duration= pkt->duration;
947  }else
948  break;
949  }
950  if(st->first_dts == AV_NOPTS_VALUE)
951  st->cur_dts= cur_dts;
952 }
953 
955  AVCodecParserContext *pc, AVPacket *pkt)
956 {
957  int num, den, presentation_delayed, delay, i;
958  int64_t offset;
959 
960  if (s->flags & AVFMT_FLAG_NOFILLIN)
961  return;
962 
963  if((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)
964  pkt->dts= AV_NOPTS_VALUE;
965 
966  if (st->codec->codec_id != CODEC_ID_H264 && pc && pc->pict_type == AV_PICTURE_TYPE_B)
967  //FIXME Set low_delay = 0 when has_b_frames = 1
968  st->codec->has_b_frames = 1;
969 
970  /* do we have a video B-frame ? */
971  delay= st->codec->has_b_frames;
972  presentation_delayed = 0;
973 
974  /* XXX: need has_b_frame, but cannot get it if the codec is
975  not initialized */
976  if (delay &&
977  pc && pc->pict_type != AV_PICTURE_TYPE_B)
978  presentation_delayed = 1;
979 
980  if(pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && pkt->dts > pkt->pts && st->pts_wrap_bits<63
981  /*&& pkt->dts-(1LL<<st->pts_wrap_bits) < pkt->pts*/){
982  pkt->dts -= 1LL<<st->pts_wrap_bits;
983  }
984 
985  // some mpeg2 in mpeg-ps lack dts (issue171 / input_file.mpg)
986  // we take the conservative approach and discard both
987  // Note, if this is misbehaving for a H.264 file then possibly presentation_delayed is not set correctly.
988  if(delay==1 && pkt->dts == pkt->pts && pkt->dts != AV_NOPTS_VALUE && presentation_delayed){
989  av_log(s, AV_LOG_DEBUG, "invalid dts/pts combination\n");
990  pkt->dts= pkt->pts= AV_NOPTS_VALUE;
991  }
992 
993  if (pkt->duration == 0) {
994  compute_frame_duration(&num, &den, st, pc, pkt);
995  if (den && num) {
996  pkt->duration = av_rescale_rnd(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num, AV_ROUND_DOWN);
997 
998  if(pkt->duration != 0 && s->packet_buffer)
999  update_initial_durations(s, st, pkt);
1000  }
1001  }
1002 
1003  /* correct timestamps with byte offset if demuxers only have timestamps
1004  on packet boundaries */
1005  if(pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size){
1006  /* this will estimate bitrate based on this frame's duration and size */
1007  offset = av_rescale(pc->offset, pkt->duration, pkt->size);
1008  if(pkt->pts != AV_NOPTS_VALUE)
1009  pkt->pts += offset;
1010  if(pkt->dts != AV_NOPTS_VALUE)
1011  pkt->dts += offset;
1012  }
1013 
1014  if (pc && pc->dts_sync_point >= 0) {
1015  // we have synchronization info from the parser
1016  int64_t den = st->codec->time_base.den * (int64_t) st->time_base.num;
1017  if (den > 0) {
1018  int64_t num = st->codec->time_base.num * (int64_t) st->time_base.den;
1019  if (pkt->dts != AV_NOPTS_VALUE) {
1020  // got DTS from the stream, update reference timestamp
1021  st->reference_dts = pkt->dts - pc->dts_ref_dts_delta * num / den;
1022  pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
1023  } else if (st->reference_dts != AV_NOPTS_VALUE) {
1024  // compute DTS based on reference timestamp
1025  pkt->dts = st->reference_dts + pc->dts_ref_dts_delta * num / den;
1026  pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
1027  }
1028  if (pc->dts_sync_point > 0)
1029  st->reference_dts = pkt->dts; // new reference
1030  }
1031  }
1032 
1033  /* This may be redundant, but it should not hurt. */
1034  if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
1035  presentation_delayed = 1;
1036 
1037 // av_log(NULL, AV_LOG_DEBUG, "IN delayed:%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64" st:%d pc:%p\n", presentation_delayed, pkt->pts, pkt->dts, st->cur_dts, pkt->stream_index, pc);
1038  /* interpolate PTS and DTS if they are not present */
1039  //We skip H264 currently because delay and has_b_frames are not reliably set
1040  if((delay==0 || (delay==1 && pc)) && st->codec->codec_id != CODEC_ID_H264){
1041  if (presentation_delayed) {
1042  /* DTS = decompression timestamp */
1043  /* PTS = presentation timestamp */
1044  if (pkt->dts == AV_NOPTS_VALUE)
1045  pkt->dts = st->last_IP_pts;
1046  update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts);
1047  if (pkt->dts == AV_NOPTS_VALUE)
1048  pkt->dts = st->cur_dts;
1049 
1050  /* this is tricky: the dts must be incremented by the duration
1051  of the frame we are displaying, i.e. the last I- or P-frame */
1052  if (st->last_IP_duration == 0)
1053  st->last_IP_duration = pkt->duration;
1054  if(pkt->dts != AV_NOPTS_VALUE)
1055  st->cur_dts = pkt->dts + st->last_IP_duration;
1056  st->last_IP_duration = pkt->duration;
1057  st->last_IP_pts= pkt->pts;
1058  /* cannot compute PTS if not present (we can compute it only
1059  by knowing the future */
1060  } else if(pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE || pkt->duration){
1061  if(pkt->pts != AV_NOPTS_VALUE && pkt->duration){
1062  int64_t old_diff= FFABS(st->cur_dts - pkt->duration - pkt->pts);
1063  int64_t new_diff= FFABS(st->cur_dts - pkt->pts);
1064  if(old_diff < new_diff && old_diff < (pkt->duration>>3)){
1065  pkt->pts += pkt->duration;
1066  // av_log(NULL, AV_LOG_DEBUG, "id:%d old:%"PRId64" new:%"PRId64" dur:%d cur:%"PRId64" size:%d\n", pkt->stream_index, old_diff, new_diff, pkt->duration, st->cur_dts, pkt->size);
1067  }
1068  }
1069 
1070  /* presentation is not delayed : PTS and DTS are the same */
1071  if(pkt->pts == AV_NOPTS_VALUE)
1072  pkt->pts = pkt->dts;
1073  update_initial_timestamps(s, pkt->stream_index, pkt->pts, pkt->pts);
1074  if(pkt->pts == AV_NOPTS_VALUE)
1075  pkt->pts = st->cur_dts;
1076  pkt->dts = pkt->pts;
1077  if(pkt->pts != AV_NOPTS_VALUE)
1078  st->cur_dts = pkt->pts + pkt->duration;
1079  }
1080  }
1081 
1082  if(pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
1083  st->pts_buffer[0]= pkt->pts;
1084  for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
1085  FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
1086  if(pkt->dts == AV_NOPTS_VALUE)
1087  pkt->dts= st->pts_buffer[0];
1088  if(st->codec->codec_id == CODEC_ID_H264){ // we skipped it above so we try here
1089  update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts); // this should happen on the first packet
1090  }
1091  if(pkt->dts > st->cur_dts)
1092  st->cur_dts = pkt->dts;
1093  }
1094 
1095 // av_log(NULL, AV_LOG_ERROR, "OUTdelayed:%d/%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64"\n", presentation_delayed, delay, pkt->pts, pkt->dts, st->cur_dts);
1096 
1097  /* update flags */
1098  if(is_intra_only(st->codec))
1099  pkt->flags |= AV_PKT_FLAG_KEY;
1100  else if (pc) {
1101  pkt->flags = 0;
1102  /* keyframe computation */
1103  if (pc->key_frame == 1)
1104  pkt->flags |= AV_PKT_FLAG_KEY;
1105  else if (pc->key_frame == -1 && pc->pict_type == AV_PICTURE_TYPE_I)
1106  pkt->flags |= AV_PKT_FLAG_KEY;
1107  }
1108  if (pc)
1110 }
1111 
1112 
1114 {
1115  AVStream *st;
1116  int len, ret, i;
1117 
1118  av_init_packet(pkt);
1119 
1120  for(;;) {
1121  /* select current input stream component */
1122  st = s->cur_st;
1123  if (st) {
1124  if (!st->need_parsing || !st->parser) {
1125  /* no parsing needed: we just output the packet as is */
1126  /* raw data support */
1127  *pkt = st->cur_pkt; st->cur_pkt.data= NULL;
1128  compute_pkt_fields(s, st, NULL, pkt);
1129  s->cur_st = NULL;
1130  if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
1131  (pkt->flags & AV_PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
1132  ff_reduce_index(s, st->index);
1133  av_add_index_entry(st, pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME);
1134  }
1135  break;
1136  } else if (st->cur_len > 0 && st->discard < AVDISCARD_ALL) {
1137  len = av_parser_parse2(st->parser, st->codec, &pkt->data, &pkt->size,
1138  st->cur_ptr, st->cur_len,
1139  st->cur_pkt.pts, st->cur_pkt.dts,
1140  st->cur_pkt.pos);
1141  st->cur_pkt.pts = AV_NOPTS_VALUE;
1142  st->cur_pkt.dts = AV_NOPTS_VALUE;
1143  /* increment read pointer */
1144  st->cur_ptr += len;
1145  st->cur_len -= len;
1146 
1147  /* return packet if any */
1148  if (pkt->size) {
1149  got_packet:
1150  pkt->duration = 0;
1151  pkt->stream_index = st->index;
1152  pkt->pts = st->parser->pts;
1153  pkt->dts = st->parser->dts;
1154  pkt->pos = st->parser->pos;
1155  if(pkt->data == st->cur_pkt.data && pkt->size == st->cur_pkt.size){
1156  s->cur_st = NULL;
1157  pkt->destruct= st->cur_pkt.destruct;
1158  st->cur_pkt.destruct= NULL;
1159  st->cur_pkt.data = NULL;
1160  assert(st->cur_len == 0);
1161  }else{
1162  pkt->destruct = NULL;
1163  }
1164  compute_pkt_fields(s, st, st->parser, pkt);
1165 
1166  if((s->iformat->flags & AVFMT_GENERIC_INDEX) && pkt->flags & AV_PKT_FLAG_KEY){
1167  ff_reduce_index(s, st->index);
1168  av_add_index_entry(st, st->parser->frame_offset, pkt->dts,
1169  0, 0, AVINDEX_KEYFRAME);
1170  }
1171 
1172  break;
1173  }
1174  } else {
1175  /* free packet */
1176  av_free_packet(&st->cur_pkt);
1177  s->cur_st = NULL;
1178  }
1179  } else {
1180  AVPacket cur_pkt;
1181  /* read next packet */
1182  ret = av_read_packet(s, &cur_pkt);
1183  if (ret < 0) {
1184  if (ret == AVERROR(EAGAIN))
1185  return ret;
1186  /* return the last frames, if any */
1187  for(i = 0; i < s->nb_streams; i++) {
1188  st = s->streams[i];
1189  if (st->parser && st->need_parsing) {
1190  av_parser_parse2(st->parser, st->codec,
1191  &pkt->data, &pkt->size,
1192  NULL, 0,
1194  AV_NOPTS_VALUE);
1195  if (pkt->size)
1196  goto got_packet;
1197  }
1198  }
1199  /* no more packets: really terminate parsing */
1200  return ret;
1201  }
1202  st = s->streams[cur_pkt.stream_index];
1203  st->cur_pkt= cur_pkt;
1204 
1205  if(st->cur_pkt.pts != AV_NOPTS_VALUE &&
1206  st->cur_pkt.dts != AV_NOPTS_VALUE &&
1207  st->cur_pkt.pts < st->cur_pkt.dts){
1208  av_log(s, AV_LOG_WARNING, "Invalid timestamps stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d\n",
1209  st->cur_pkt.stream_index,
1210  st->cur_pkt.pts,
1211  st->cur_pkt.dts,
1212  st->cur_pkt.size);
1213 // av_free_packet(&st->cur_pkt);
1214 // return -1;
1215  }
1216 
1217  if(s->debug & FF_FDEBUG_TS)
1218  av_log(s, AV_LOG_DEBUG, "av_read_packet stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
1219  st->cur_pkt.stream_index,
1220  st->cur_pkt.pts,
1221  st->cur_pkt.dts,
1222  st->cur_pkt.size,
1223  st->cur_pkt.duration,
1224  st->cur_pkt.flags);
1225 
1226  s->cur_st = st;
1227  st->cur_ptr = st->cur_pkt.data;
1228  st->cur_len = st->cur_pkt.size;
1229  if (st->need_parsing && !st->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) {
1230  st->parser = av_parser_init(st->codec->codec_id);
1231  if (!st->parser) {
1232  /* no parser available: just output the raw packets */
1234  }else if(st->need_parsing == AVSTREAM_PARSE_HEADERS){
1236  }else if(st->need_parsing == AVSTREAM_PARSE_FULL_ONCE){
1237  st->parser->flags |= PARSER_FLAG_ONCE;
1238  }
1239  }
1240  }
1241  }
1242  if(s->debug & FF_FDEBUG_TS)
1243  av_log(s, AV_LOG_DEBUG, "read_frame_internal stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
1244  pkt->stream_index,
1245  pkt->pts,
1246  pkt->dts,
1247  pkt->size,
1248  pkt->duration,
1249  pkt->flags);
1250 
1251  return 0;
1252 }
1253 
1255 {
1256  AVPacketList *pktl = s->packet_buffer;
1257  av_assert0(pktl);
1258  *pkt = pktl->pkt;
1259  s->packet_buffer = pktl->next;
1260  av_freep(&pktl);
1261  return 0;
1262 }
1263 
1265 {
1266  const int genpts = s->flags & AVFMT_FLAG_GENPTS;
1267  int eof = 0;
1268 
1269  if (!genpts)
1270  return s->packet_buffer ? read_from_packet_buffer(s, pkt) :
1271  read_frame_internal(s, pkt);
1272 
1273  for (;;) {
1274  int ret;
1275  AVPacketList *pktl = s->packet_buffer;
1276 
1277  if (pktl) {
1278  AVPacket *next_pkt = &pktl->pkt;
1279 
1280  if (next_pkt->dts != AV_NOPTS_VALUE) {
1281  int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;
1282  while (pktl && next_pkt->pts == AV_NOPTS_VALUE) {
1283  if (pktl->pkt.stream_index == next_pkt->stream_index &&
1284  (av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2LL << (wrap_bits - 1)) < 0) &&
1285  av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2LL << (wrap_bits - 1))) { //not b frame
1286  next_pkt->pts = pktl->pkt.dts;
1287  }
1288  pktl = pktl->next;
1289  }
1290  pktl = s->packet_buffer;
1291  }
1292 
1293  /* read packet from packet buffer, if there is data */
1294  if (!(next_pkt->pts == AV_NOPTS_VALUE &&
1295  next_pkt->dts != AV_NOPTS_VALUE && !eof))
1296  return read_from_packet_buffer(s, pkt);
1297  }
1298 
1299  ret = read_frame_internal(s, pkt);
1300  if (ret < 0) {
1301  if (pktl && ret != AVERROR(EAGAIN)) {
1302  eof = 1;
1303  continue;
1304  } else
1305  return ret;
1306  }
1307 
1309  &s->packet_buffer_end)) < 0)
1310  return AVERROR(ENOMEM);
1311  }
1312 }
1313 
1314 /* XXX: suppress the packet queue */
1316 {
1317  AVPacketList *pktl;
1318 
1319  for(;;) {
1320  pktl = s->packet_buffer;
1321  if (!pktl)
1322  break;
1323  s->packet_buffer = pktl->next;
1324  av_free_packet(&pktl->pkt);
1325  av_free(pktl);
1326  }
1327  while(s->raw_packet_buffer){
1328  pktl = s->raw_packet_buffer;
1329  s->raw_packet_buffer = pktl->next;
1330  av_free_packet(&pktl->pkt);
1331  av_free(pktl);
1332  }
1333  s->packet_buffer_end=
1336 }
1337 
1338 /*******************************************************/
1339 /* seek support */
1340 
1342 {
1343  int first_audio_index = -1;
1344  int i;
1345  AVStream *st;
1346 
1347  if (s->nb_streams <= 0)
1348  return -1;
1349  for(i = 0; i < s->nb_streams; i++) {
1350  st = s->streams[i];
1351  if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1352  return i;
1353  }
1354  if (first_audio_index < 0 && st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1355  first_audio_index = i;
1356  }
1357  return first_audio_index >= 0 ? first_audio_index : 0;
1358 }
1359 
1364 {
1365  AVStream *st;
1366  int i, j;
1367 
1368  flush_packet_queue(s);
1369 
1370  s->cur_st = NULL;
1371 
1372  /* for each stream, reset read state */
1373  for(i = 0; i < s->nb_streams; i++) {
1374  st = s->streams[i];
1375 
1376  if (st->parser) {
1377  av_parser_close(st->parser);
1378  st->parser = NULL;
1379  av_free_packet(&st->cur_pkt);
1380  }
1382  st->cur_dts = AV_NOPTS_VALUE; /* we set the current DTS to an unspecified origin */
1384  /* fail safe */
1385  st->cur_ptr = NULL;
1386  st->cur_len = 0;
1387 
1389 
1390  for(j=0; j<MAX_REORDER_DELAY+1; j++)
1391  st->pts_buffer[j]= AV_NOPTS_VALUE;
1392  }
1393 }
1394 
1395 #if FF_API_SEEK_PUBLIC
1396 void av_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp)
1397 {
1398  ff_update_cur_dts(s, ref_st, timestamp);
1399 }
1400 #endif
1401 
1402 void ff_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp)
1403 {
1404  int i;
1405 
1406  for(i = 0; i < s->nb_streams; i++) {
1407  AVStream *st = s->streams[i];
1408 
1409  st->cur_dts = av_rescale(timestamp,
1410  st->time_base.den * (int64_t)ref_st->time_base.num,
1411  st->time_base.num * (int64_t)ref_st->time_base.den);
1412  }
1413 }
1414 
1415 void ff_reduce_index(AVFormatContext *s, int stream_index)
1416 {
1417  AVStream *st= s->streams[stream_index];
1418  unsigned int max_entries= s->max_index_size / sizeof(AVIndexEntry);
1419 
1420  if((unsigned)st->nb_index_entries >= max_entries){
1421  int i;
1422  for(i=0; 2*i<st->nb_index_entries; i++)
1423  st->index_entries[i]= st->index_entries[2*i];
1424  st->nb_index_entries= i;
1425  }
1426 }
1427 
1428 int ff_add_index_entry(AVIndexEntry **index_entries,
1429  int *nb_index_entries,
1430  unsigned int *index_entries_allocated_size,
1431  int64_t pos, int64_t timestamp, int size, int distance, int flags)
1432 {
1433  AVIndexEntry *entries, *ie;
1434  int index;
1435 
1436  if((unsigned)*nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1437  return -1;
1438 
1439  entries = av_fast_realloc(*index_entries,
1440  index_entries_allocated_size,
1441  (*nb_index_entries + 1) *
1442  sizeof(AVIndexEntry));
1443  if(!entries)
1444  return -1;
1445 
1446  *index_entries= entries;
1447 
1448  index= ff_index_search_timestamp(*index_entries, *nb_index_entries, timestamp, AVSEEK_FLAG_ANY);
1449 
1450  if(index<0){
1451  index= (*nb_index_entries)++;
1452  ie= &entries[index];
1453  assert(index==0 || ie[-1].timestamp < timestamp);
1454  }else{
1455  ie= &entries[index];
1456  if(ie->timestamp != timestamp){
1457  if(ie->timestamp <= timestamp)
1458  return -1;
1459  memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(*nb_index_entries - index));
1460  (*nb_index_entries)++;
1461  }else if(ie->pos == pos && distance < ie->min_distance) //do not reduce the distance
1462  distance= ie->min_distance;
1463  }
1464 
1465  ie->pos = pos;
1466  ie->timestamp = timestamp;
1467  ie->min_distance= distance;
1468  ie->size= size;
1469  ie->flags = flags;
1470 
1471  return index;
1472 }
1473 
1475  int64_t pos, int64_t timestamp, int size, int distance, int flags)
1476 {
1478  &st->index_entries_allocated_size, pos,
1479  timestamp, size, distance, flags);
1480 }
1481 
1482 int ff_index_search_timestamp(const AVIndexEntry *entries, int nb_entries,
1483  int64_t wanted_timestamp, int flags)
1484 {
1485  int a, b, m;
1486  int64_t timestamp;
1487 
1488  a = - 1;
1489  b = nb_entries;
1490 
1491  //optimize appending index entries at the end
1492  if(b && entries[b-1].timestamp < wanted_timestamp)
1493  a= b-1;
1494 
1495  while (b - a > 1) {
1496  m = (a + b) >> 1;
1497  timestamp = entries[m].timestamp;
1498  if(timestamp >= wanted_timestamp)
1499  b = m;
1500  if(timestamp <= wanted_timestamp)
1501  a = m;
1502  }
1503  m= (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
1504 
1505  if(!(flags & AVSEEK_FLAG_ANY)){
1506  while(m>=0 && m<nb_entries && !(entries[m].flags & AVINDEX_KEYFRAME)){
1507  m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
1508  }
1509  }
1510 
1511  if(m == nb_entries)
1512  return -1;
1513  return m;
1514 }
1515 
1516 int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
1517  int flags)
1518 {
1520  wanted_timestamp, flags);
1521 }
1522 
1523 #if FF_API_SEEK_PUBLIC
1524 int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1525  return ff_seek_frame_binary(s, stream_index, target_ts, flags);
1526 }
1527 #endif
1528 
1529 int ff_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
1530 {
1531  AVInputFormat *avif= s->iformat;
1532  int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
1533  int64_t ts_min, ts_max, ts;
1534  int index;
1535  int64_t ret;
1536  AVStream *st;
1537 
1538  if (stream_index < 0)
1539  return -1;
1540 
1541  av_dlog(s, "read_seek: %d %"PRId64"\n", stream_index, target_ts);
1542 
1543  ts_max=
1544  ts_min= AV_NOPTS_VALUE;
1545  pos_limit= -1; //gcc falsely says it may be uninitialized
1546 
1547  st= s->streams[stream_index];
1548  if(st->index_entries){
1549  AVIndexEntry *e;
1550 
1551  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()
1552  index= FFMAX(index, 0);
1553  e= &st->index_entries[index];
1554 
1555  if(e->timestamp <= target_ts || e->pos == e->min_distance){
1556  pos_min= e->pos;
1557  ts_min= e->timestamp;
1558  av_dlog(s, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",
1559  pos_min,ts_min);
1560  }else{
1561  assert(index==0);
1562  }
1563 
1564  index= av_index_search_timestamp(st, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
1565  assert(index < st->nb_index_entries);
1566  if(index >= 0){
1567  e= &st->index_entries[index];
1568  assert(e->timestamp >= target_ts);
1569  pos_max= e->pos;
1570  ts_max= e->timestamp;
1571  pos_limit= pos_max - e->min_distance;
1572  av_dlog(s, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64" dts_max=%"PRId64"\n",
1573  pos_max,pos_limit, ts_max);
1574  }
1575  }
1576 
1577  pos= ff_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit, ts_min, ts_max, flags, &ts, avif->read_timestamp);
1578  if(pos<0)
1579  return -1;
1580 
1581  /* do the seek */
1582  if ((ret = avio_seek(s->pb, pos, SEEK_SET)) < 0)
1583  return ret;
1584 
1585  ff_update_cur_dts(s, st, ts);
1586 
1587  return 0;
1588 }
1589 
1590 #if FF_API_SEEK_PUBLIC
1591 int64_t av_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts,
1592  int64_t pos_min, int64_t pos_max, int64_t pos_limit,
1593  int64_t ts_min, int64_t ts_max, int flags, int64_t *ts_ret,
1594  int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ))
1595 {
1596  return ff_gen_search(s, stream_index, target_ts, pos_min, pos_max,
1597  pos_limit, ts_min, ts_max, flags, ts_ret,
1598  read_timestamp);
1599 }
1600 #endif
1601 
1602 int64_t ff_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts,
1603  int64_t pos_min, int64_t pos_max, int64_t pos_limit,
1604  int64_t ts_min, int64_t ts_max, int flags, int64_t *ts_ret,
1605  int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ))
1606 {
1607  int64_t pos, ts;
1608  int64_t start_pos, filesize;
1609  int no_change;
1610 
1611  av_dlog(s, "gen_seek: %d %"PRId64"\n", stream_index, target_ts);
1612 
1613  if(ts_min == AV_NOPTS_VALUE){
1614  pos_min = s->data_offset;
1615  ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1616  if (ts_min == AV_NOPTS_VALUE)
1617  return -1;
1618  }
1619 
1620  if(ts_max == AV_NOPTS_VALUE){
1621  int step= 1024;
1622  filesize = avio_size(s->pb);
1623  pos_max = filesize - 1;
1624  do{
1625  pos_max -= step;
1626  ts_max = read_timestamp(s, stream_index, &pos_max, pos_max + step);
1627  step += step;
1628  }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
1629  if (ts_max == AV_NOPTS_VALUE)
1630  return -1;
1631 
1632  for(;;){
1633  int64_t tmp_pos= pos_max + 1;
1634  int64_t tmp_ts= read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
1635  if(tmp_ts == AV_NOPTS_VALUE)
1636  break;
1637  ts_max= tmp_ts;
1638  pos_max= tmp_pos;
1639  if(tmp_pos >= filesize)
1640  break;
1641  }
1642  pos_limit= pos_max;
1643  }
1644 
1645  if(ts_min > ts_max){
1646  return -1;
1647  }else if(ts_min == ts_max){
1648  pos_limit= pos_min;
1649  }
1650 
1651  no_change=0;
1652  while (pos_min < pos_limit) {
1653  av_dlog(s, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64" dts_max=%"PRId64"\n",
1654  pos_min, pos_max, ts_min, ts_max);
1655  assert(pos_limit <= pos_max);
1656 
1657  if(no_change==0){
1658  int64_t approximate_keyframe_distance= pos_max - pos_limit;
1659  // interpolate position (better than dichotomy)
1660  pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)
1661  + pos_min - approximate_keyframe_distance;
1662  }else if(no_change==1){
1663  // bisection, if interpolation failed to change min or max pos last time
1664  pos = (pos_min + pos_limit)>>1;
1665  }else{
1666  /* linear search if bisection failed, can only happen if there
1667  are very few or no keyframes between min/max */
1668  pos=pos_min;
1669  }
1670  if(pos <= pos_min)
1671  pos= pos_min + 1;
1672  else if(pos > pos_limit)
1673  pos= pos_limit;
1674  start_pos= pos;
1675 
1676  ts = read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
1677  if(pos == pos_max)
1678  no_change++;
1679  else
1680  no_change=0;
1681  av_dlog(s, "%"PRId64" %"PRId64" %"PRId64" / %"PRId64" %"PRId64" %"PRId64" target:%"PRId64" limit:%"PRId64" start:%"PRId64" noc:%d\n",
1682  pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts,
1683  pos_limit, start_pos, no_change);
1684  if(ts == AV_NOPTS_VALUE){
1685  av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
1686  return -1;
1687  }
1688  assert(ts != AV_NOPTS_VALUE);
1689  if (target_ts <= ts) {
1690  pos_limit = start_pos - 1;
1691  pos_max = pos;
1692  ts_max = ts;
1693  }
1694  if (target_ts >= ts) {
1695  pos_min = pos;
1696  ts_min = ts;
1697  }
1698  }
1699 
1700  pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
1701  ts = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min : ts_max;
1702  pos_min = pos;
1703  ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1704  pos_min++;
1705  ts_max = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1706  av_dlog(s, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n",
1707  pos, ts_min, target_ts, ts_max);
1708  *ts_ret= ts;
1709  return pos;
1710 }
1711 
1712 static int seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){
1713  int64_t pos_min, pos_max;
1714 #if 0
1715  AVStream *st;
1716 
1717  if (stream_index < 0)
1718  return -1;
1719 
1720  st= s->streams[stream_index];
1721 #endif
1722 
1723  pos_min = s->data_offset;
1724  pos_max = avio_size(s->pb) - 1;
1725 
1726  if (pos < pos_min) pos= pos_min;
1727  else if(pos > pos_max) pos= pos_max;
1728 
1729  avio_seek(s->pb, pos, SEEK_SET);
1730 
1731 #if 0
1732  av_update_cur_dts(s, st, ts);
1733 #endif
1734  return 0;
1735 }
1736 
1738  int stream_index, int64_t timestamp, int flags)
1739 {
1740  int index;
1741  int64_t ret;
1742  AVStream *st;
1743  AVIndexEntry *ie;
1744 
1745  st = s->streams[stream_index];
1746 
1747  index = av_index_search_timestamp(st, timestamp, flags);
1748 
1749  if(index < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
1750  return -1;
1751 
1752  if(index < 0 || index==st->nb_index_entries-1){
1753  AVPacket pkt;
1754 
1755  if(st->nb_index_entries){
1756  assert(st->index_entries);
1757  ie= &st->index_entries[st->nb_index_entries-1];
1758  if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
1759  return ret;
1760  ff_update_cur_dts(s, st, ie->timestamp);
1761  }else{
1762  if ((ret = avio_seek(s->pb, s->data_offset, SEEK_SET)) < 0)
1763  return ret;
1764  }
1765  for (;;) {
1766  int read_status;
1767  do{
1768  read_status = av_read_frame(s, &pkt);
1769  } while (read_status == AVERROR(EAGAIN));
1770  if (read_status < 0)
1771  break;
1772  av_free_packet(&pkt);
1773  if(stream_index == pkt.stream_index){
1774  if((pkt.flags & AV_PKT_FLAG_KEY) && pkt.dts > timestamp)
1775  break;
1776  }
1777  }
1778  index = av_index_search_timestamp(st, timestamp, flags);
1779  }
1780  if (index < 0)
1781  return -1;
1782 
1784  if (s->iformat->read_seek){
1785  if(s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
1786  return 0;
1787  }
1788  ie = &st->index_entries[index];
1789  if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
1790  return ret;
1791  ff_update_cur_dts(s, st, ie->timestamp);
1792 
1793  return 0;
1794 }
1795 
1796 int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1797 {
1798  int ret;
1799  AVStream *st;
1800 
1801  if (flags & AVSEEK_FLAG_BYTE) {
1802  if (s->iformat->flags & AVFMT_NO_BYTE_SEEK)
1803  return -1;
1805  return seek_frame_byte(s, stream_index, timestamp, flags);
1806  }
1807 
1808  if(stream_index < 0){
1809  stream_index= av_find_default_stream_index(s);
1810  if(stream_index < 0)
1811  return -1;
1812 
1813  st= s->streams[stream_index];
1814  /* timestamp for default must be expressed in AV_TIME_BASE units */
1815  timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1816  }
1817 
1818  /* first, we try the format specific seek */
1819  if (s->iformat->read_seek) {
1821  ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
1822  } else
1823  ret = -1;
1824  if (ret >= 0) {
1825  return 0;
1826  }
1827 
1828  if (s->iformat->read_timestamp && !(s->iformat->flags & AVFMT_NOBINSEARCH)) {
1830  return ff_seek_frame_binary(s, stream_index, timestamp, flags);
1831  } else if (!(s->iformat->flags & AVFMT_NOGENSEARCH)) {
1833  return seek_frame_generic(s, stream_index, timestamp, flags);
1834  }
1835  else
1836  return -1;
1837 }
1838 
1839 int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
1840 {
1841  if(min_ts > ts || max_ts < ts)
1842  return -1;
1843 
1844  if (s->iformat->read_seek2) {
1846  return s->iformat->read_seek2(s, stream_index, min_ts, ts, max_ts, flags);
1847  }
1848 
1849  if(s->iformat->read_timestamp){
1850  //try to seek via read_timestamp()
1851  }
1852 
1853  //Fallback to old API if new is not implemented but old is
1854  //Note the old has somewat different sematics
1855  if(s->iformat->read_seek || 1)
1856  return av_seek_frame(s, stream_index, ts, flags | ((uint64_t)ts - min_ts > (uint64_t)max_ts - ts ? AVSEEK_FLAG_BACKWARD : 0));
1857 
1858  // try some generic seek like seek_frame_generic() but with new ts semantics
1859 }
1860 
1861 /*******************************************************/
1862 
1869 {
1870  int i;
1871  AVStream *st;
1872 
1873  for(i = 0;i < ic->nb_streams; i++) {
1874  st = ic->streams[i];
1875  if (st->duration != AV_NOPTS_VALUE)
1876  return 1;
1877  }
1878  return 0;
1879 }
1880 
1887 {
1888  int64_t start_time, start_time1, end_time, end_time1;
1889  int64_t duration, duration1, filesize;
1890  int i;
1891  AVStream *st;
1892 
1893  start_time = INT64_MAX;
1894  end_time = INT64_MIN;
1895  duration = INT64_MIN;
1896  for(i = 0;i < ic->nb_streams; i++) {
1897  st = ic->streams[i];
1898  if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
1899  start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
1900  start_time = FFMIN(start_time, start_time1);
1901  if (st->duration != AV_NOPTS_VALUE) {
1902  end_time1 = start_time1
1904  end_time = FFMAX(end_time, end_time1);
1905  }
1906  }
1907  if (st->duration != AV_NOPTS_VALUE) {
1908  duration1 = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1909  duration = FFMAX(duration, duration1);
1910  }
1911  }
1912  if (start_time != INT64_MAX) {
1913  ic->start_time = start_time;
1914  if (end_time != INT64_MIN)
1915  duration = FFMAX(duration, end_time - start_time);
1916  }
1917  if (duration != INT64_MIN) {
1918  ic->duration = duration;
1919  if (ic->pb && (filesize = avio_size(ic->pb)) > 0) {
1920  /* compute the bitrate */
1921  ic->bit_rate = (double)filesize * 8.0 * AV_TIME_BASE /
1922  (double)ic->duration;
1923  }
1924  }
1925 }
1926 
1928 {
1929  int i;
1930  AVStream *st;
1931 
1933  for(i = 0;i < ic->nb_streams; i++) {
1934  st = ic->streams[i];
1935  if (st->start_time == AV_NOPTS_VALUE) {
1936  if(ic->start_time != AV_NOPTS_VALUE)
1938  if(ic->duration != AV_NOPTS_VALUE)
1940  }
1941  }
1942 }
1943 
1945 {
1946  int64_t filesize, duration;
1947  int bit_rate, i;
1948  AVStream *st;
1949 
1950  /* if bit_rate is already set, we believe it */
1951  if (ic->bit_rate <= 0) {
1952  bit_rate = 0;
1953  for(i=0;i<ic->nb_streams;i++) {
1954  st = ic->streams[i];
1955  if (st->codec->bit_rate > 0) {
1956  if (INT_MAX - st->codec->bit_rate < bit_rate) {
1957  bit_rate = 0;
1958  break;
1959  }
1960  bit_rate += st->codec->bit_rate;
1961  }
1962  }
1963  ic->bit_rate = bit_rate;
1964  }
1965 
1966  /* if duration is already set, we believe it */
1967  if (ic->duration == AV_NOPTS_VALUE &&
1968  ic->bit_rate != 0) {
1969  filesize = ic->pb ? avio_size(ic->pb) : 0;
1970  if (filesize > 0) {
1971  for(i = 0; i < ic->nb_streams; i++) {
1972  st = ic->streams[i];
1973  duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);
1974  if (st->duration == AV_NOPTS_VALUE)
1975  st->duration = duration;
1976  }
1977  }
1978  }
1979 }
1980 
1981 #define DURATION_MAX_READ_SIZE 250000
1982 #define DURATION_MAX_RETRY 3
1983 
1984 /* only usable for MPEG-PS streams */
1985 static void estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
1986 {
1987  AVPacket pkt1, *pkt = &pkt1;
1988  AVStream *st;
1989  int read_size, i, ret;
1990  int64_t end_time;
1991  int64_t filesize, offset, duration;
1992  int retry=0;
1993 
1994  ic->cur_st = NULL;
1995 
1996  /* flush packet queue */
1997  flush_packet_queue(ic);
1998 
1999  for (i=0; i<ic->nb_streams; i++) {
2000  st = ic->streams[i];
2001  if (st->start_time == AV_NOPTS_VALUE && st->first_dts == AV_NOPTS_VALUE)
2002  av_log(st->codec, AV_LOG_WARNING, "start time is not set in estimate_timings_from_pts\n");
2003 
2004  if (st->parser) {
2005  av_parser_close(st->parser);
2006  st->parser= NULL;
2007  av_free_packet(&st->cur_pkt);
2008  }
2009  }
2010 
2011  /* estimate the end time (duration) */
2012  /* XXX: may need to support wrapping */
2013  filesize = ic->pb ? avio_size(ic->pb) : 0;
2014  end_time = AV_NOPTS_VALUE;
2015  do{
2016  offset = filesize - (DURATION_MAX_READ_SIZE<<retry);
2017  if (offset < 0)
2018  offset = 0;
2019 
2020  avio_seek(ic->pb, offset, SEEK_SET);
2021  read_size = 0;
2022  for(;;) {
2023  if (read_size >= DURATION_MAX_READ_SIZE<<(FFMAX(retry-1,0)))
2024  break;
2025 
2026  do {
2027  ret = av_read_packet(ic, pkt);
2028  } while(ret == AVERROR(EAGAIN));
2029  if (ret != 0)
2030  break;
2031  read_size += pkt->size;
2032  st = ic->streams[pkt->stream_index];
2033  if (pkt->pts != AV_NOPTS_VALUE &&
2034  (st->start_time != AV_NOPTS_VALUE ||
2035  st->first_dts != AV_NOPTS_VALUE)) {
2036  duration = end_time = pkt->pts;
2037  if (st->start_time != AV_NOPTS_VALUE)
2038  duration -= st->start_time;
2039  else
2040  duration -= st->first_dts;
2041  if (duration < 0)
2042  duration += 1LL<<st->pts_wrap_bits;
2043  if (duration > 0) {
2044  if (st->duration == AV_NOPTS_VALUE || st->duration < duration)
2045  st->duration = duration;
2046  }
2047  }
2048  av_free_packet(pkt);
2049  }
2050  }while( end_time==AV_NOPTS_VALUE
2051  && filesize > (DURATION_MAX_READ_SIZE<<retry)
2052  && ++retry <= DURATION_MAX_RETRY);
2053 
2055 
2056  avio_seek(ic->pb, old_offset, SEEK_SET);
2057  for (i=0; i<ic->nb_streams; i++) {
2058  st= ic->streams[i];
2059  st->cur_dts= st->first_dts;
2062  }
2063 }
2064 
2065 static void estimate_timings(AVFormatContext *ic, int64_t old_offset)
2066 {
2067  int64_t file_size;
2068 
2069  /* get the file size, if possible */
2070  if (ic->iformat->flags & AVFMT_NOFILE) {
2071  file_size = 0;
2072  } else {
2073  file_size = avio_size(ic->pb);
2074  file_size = FFMAX(0, file_size);
2075  }
2076 
2077  if ((!strcmp(ic->iformat->name, "mpeg") ||
2078  !strcmp(ic->iformat->name, "mpegts")) &&
2079  file_size && ic->pb->seekable) {
2080  /* get accurate estimate from the PTSes */
2081  estimate_timings_from_pts(ic, old_offset);
2082  } else if (has_duration(ic)) {
2083  /* at least one component has timings - we use them for all
2084  the components */
2086  } else {
2087  av_log(ic, AV_LOG_WARNING, "Estimating duration from bitrate, this may be inaccurate\n");
2088  /* less precise: use bitrate info */
2090  }
2092 
2093  {
2094  int i;
2095  AVStream av_unused *st;
2096  for(i = 0;i < ic->nb_streams; i++) {
2097  st = ic->streams[i];
2098  av_dlog(ic, "%d: start_time: %0.3f duration: %0.3f\n", i,
2099  (double) st->start_time / AV_TIME_BASE,
2100  (double) st->duration / AV_TIME_BASE);
2101  }
2102  av_dlog(ic, "stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
2103  (double) ic->start_time / AV_TIME_BASE,
2104  (double) ic->duration / AV_TIME_BASE,
2105  ic->bit_rate / 1000);
2106  }
2107 }
2108 
2110 {
2111  int val;
2112  switch (avctx->codec_type) {
2113  case AVMEDIA_TYPE_AUDIO:
2114  val = avctx->sample_rate && avctx->channels && avctx->sample_fmt != AV_SAMPLE_FMT_NONE;
2115  if (!avctx->frame_size &&
2116  (avctx->codec_id == CODEC_ID_VORBIS ||
2117  avctx->codec_id == CODEC_ID_AAC ||
2118  avctx->codec_id == CODEC_ID_MP1 ||
2119  avctx->codec_id == CODEC_ID_MP2 ||
2120  avctx->codec_id == CODEC_ID_MP3 ||
2121  avctx->codec_id == CODEC_ID_CELT))
2122  return 0;
2123  break;
2124  case AVMEDIA_TYPE_VIDEO:
2125  val = avctx->width && avctx->pix_fmt != PIX_FMT_NONE;
2126  break;
2127  default:
2128  val = 1;
2129  break;
2130  }
2131  return avctx->codec_id != CODEC_ID_NONE && val != 0;
2132 }
2133 
2135 {
2136  return st->codec->codec_id != CODEC_ID_H264 ||
2137  st->info->nb_decoded_frames >= 6;
2138 }
2139 
2140 /* returns 1 or 0 if or if not decoded data was returned, or a negative error */
2142 {
2143  AVCodec *codec;
2144  int got_picture = 1, ret = 0;
2145  AVFrame picture;
2146  AVPacket pkt = *avpkt;
2147 
2148  if (!avcodec_is_open(st->codec)) {
2149  AVDictionary *thread_opt = NULL;
2150 
2151  codec = st->codec->codec ? st->codec->codec :
2153 
2154  if (!codec)
2155  return -1;
2156 
2157  /* force thread count to 1 since the h264 decoder will not extract SPS
2158  * and PPS to extradata during multi-threaded decoding */
2159  av_dict_set(options ? options : &thread_opt, "threads", "1", 0);
2160  ret = avcodec_open2(st->codec, codec, options ? options : &thread_opt);
2161  if (!options)
2162  av_dict_free(&thread_opt);
2163  if (ret < 0)
2164  return ret;
2165  }
2166 
2167  while ((pkt.size > 0 || (!pkt.data && got_picture)) &&
2168  ret >= 0 &&
2169  (!has_codec_parameters(st->codec) ||
2172  got_picture = 0;
2173  avcodec_get_frame_defaults(&picture);
2174  switch(st->codec->codec_type) {
2175  case AVMEDIA_TYPE_VIDEO:
2176  ret = avcodec_decode_video2(st->codec, &picture,
2177  &got_picture, &pkt);
2178  break;
2179  case AVMEDIA_TYPE_AUDIO:
2180  ret = avcodec_decode_audio4(st->codec, &picture, &got_picture, &pkt);
2181  break;
2182  default:
2183  break;
2184  }
2185  if (ret >= 0) {
2186  if (got_picture)
2187  st->info->nb_decoded_frames++;
2188  pkt.data += ret;
2189  pkt.size -= ret;
2190  ret = got_picture;
2191  }
2192  }
2193  return ret;
2194 }
2195 
2196 unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum CodecID id)
2197 {
2198  while (tags->id != CODEC_ID_NONE) {
2199  if (tags->id == id)
2200  return tags->tag;
2201  tags++;
2202  }
2203  return 0;
2204 }
2205 
2206 enum CodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
2207 {
2208  int i;
2209  for(i=0; tags[i].id != CODEC_ID_NONE;i++) {
2210  if(tag == tags[i].tag)
2211  return tags[i].id;
2212  }
2213  for(i=0; tags[i].id != CODEC_ID_NONE; i++) {
2214  if (avpriv_toupper4(tag) == avpriv_toupper4(tags[i].tag))
2215  return tags[i].id;
2216  }
2217  return CODEC_ID_NONE;
2218 }
2219 
2220 unsigned int av_codec_get_tag(const AVCodecTag * const *tags, enum CodecID id)
2221 {
2222  int i;
2223  for(i=0; tags && tags[i]; i++){
2224  int tag= ff_codec_get_tag(tags[i], id);
2225  if(tag) return tag;
2226  }
2227  return 0;
2228 }
2229 
2230 enum CodecID av_codec_get_id(const AVCodecTag * const *tags, unsigned int tag)
2231 {
2232  int i;
2233  for(i=0; tags && tags[i]; i++){
2234  enum CodecID id= ff_codec_get_id(tags[i], tag);
2235  if(id!=CODEC_ID_NONE) return id;
2236  }
2237  return CODEC_ID_NONE;
2238 }
2239 
2241 {
2242  unsigned int i, j;
2243  int64_t max_time = s->duration + ((s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time);
2244 
2245  for (i = 0; i < s->nb_chapters; i++)
2246  if (s->chapters[i]->end == AV_NOPTS_VALUE) {
2247  AVChapter *ch = s->chapters[i];
2248  int64_t end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q, ch->time_base)
2249  : INT64_MAX;
2250 
2251  for (j = 0; j < s->nb_chapters; j++) {
2252  AVChapter *ch1 = s->chapters[j];
2253  int64_t next_start = av_rescale_q(ch1->start, ch1->time_base, ch->time_base);
2254  if (j != i && next_start > ch->start && next_start < end)
2255  end = next_start;
2256  }
2257  ch->end = (end == INT64_MAX) ? ch->start : end;
2258  }
2259 }
2260 
2261 static int get_std_framerate(int i){
2262  if(i<60*12) return i*1001;
2263  else return ((const int[]){24,30,60,12,15})[i-60*12]*1000*12;
2264 }
2265 
2266 /*
2267  * Is the time base unreliable.
2268  * This is a heuristic to balance between quick acceptance of the values in
2269  * the headers vs. some extra checks.
2270  * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
2271  * MPEG-2 commonly misuses field repeat flags to store different framerates.
2272  * And there are "variable" fps files this needs to detect as well.
2273  */
2275  if( c->time_base.den >= 101L*c->time_base.num
2276  || c->time_base.den < 5L*c->time_base.num
2277 /* || c->codec_tag == AV_RL32("DIVX")
2278  || c->codec_tag == AV_RL32("XVID")*/
2279  || c->codec_id == CODEC_ID_MPEG2VIDEO
2280  || c->codec_id == CODEC_ID_H264
2281  )
2282  return 1;
2283  return 0;
2284 }
2285 
2286 #if FF_API_FORMAT_PARAMETERS
2287 int av_find_stream_info(AVFormatContext *ic)
2288 {
2289  return avformat_find_stream_info(ic, NULL);
2290 }
2291 #endif
2292 
2294 {
2295  int i, count, ret, read_size, j;
2296  AVStream *st;
2297  AVPacket pkt1, *pkt;
2298  int64_t old_offset = avio_tell(ic->pb);
2299  int orig_nb_streams = ic->nb_streams; // new streams might appear, no options for those
2300 
2301  for(i=0;i<ic->nb_streams;i++) {
2302  AVCodec *codec;
2303  AVDictionary *thread_opt = NULL;
2304  st = ic->streams[i];
2305 
2306  if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2308 /* if(!st->time_base.num)
2309  st->time_base= */
2310  if(!st->codec->time_base.num)
2311  st->codec->time_base= st->time_base;
2312  }
2313  //only for the split stuff
2314  if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE)) {
2315  st->parser = av_parser_init(st->codec->codec_id);
2316  if(st->need_parsing == AVSTREAM_PARSE_HEADERS && st->parser){
2318  }
2319  }
2320  codec = st->codec->codec ? st->codec->codec :
2322 
2323  /* force thread count to 1 since the h264 decoder will not extract SPS
2324  * and PPS to extradata during multi-threaded decoding */
2325  av_dict_set(options ? &options[i] : &thread_opt, "threads", "1", 0);
2326 
2327  /* Ensure that subtitle_header is properly set. */
2329  && codec && !st->codec->codec)
2330  avcodec_open2(st->codec, codec, options ? &options[i]
2331  : &thread_opt);
2332 
2333  //try to just open decoders, in case this is enough to get parameters
2334  if(!has_codec_parameters(st->codec)){
2335  if (codec && !st->codec->codec)
2336  avcodec_open2(st->codec, codec, options ? &options[i]
2337  : &thread_opt);
2338  }
2339  if (!options)
2340  av_dict_free(&thread_opt);
2341  }
2342 
2343  for (i=0; i<ic->nb_streams; i++) {
2344  ic->streams[i]->info->last_dts = AV_NOPTS_VALUE;
2345  }
2346 
2347  count = 0;
2348  read_size = 0;
2349  for(;;) {
2351  ret= AVERROR_EXIT;
2352  av_log(ic, AV_LOG_DEBUG, "interrupted\n");
2353  break;
2354  }
2355 
2356  /* check if one codec still needs to be handled */
2357  for(i=0;i<ic->nb_streams;i++) {
2358  int fps_analyze_framecount = 20;
2359 
2360  st = ic->streams[i];
2361  if (!has_codec_parameters(st->codec))
2362  break;
2363  /* if the timebase is coarse (like the usual millisecond precision
2364  of mkv), we need to analyze more frames to reliably arrive at
2365  the correct fps */
2366  if (av_q2d(st->time_base) > 0.0005)
2367  fps_analyze_framecount *= 2;
2368  if (ic->fps_probe_size >= 0)
2369  fps_analyze_framecount = ic->fps_probe_size;
2370  /* variable fps and no guess at the real fps */
2371  if( tb_unreliable(st->codec) && !(st->r_frame_rate.num && st->avg_frame_rate.num)
2372  && st->info->duration_count < fps_analyze_framecount
2373  && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2374  break;
2375  if(st->parser && st->parser->parser->split && !st->codec->extradata)
2376  break;
2377  if(st->first_dts == AV_NOPTS_VALUE)
2378  break;
2379  }
2380  if (i == ic->nb_streams) {
2381  /* NOTE: if the format has no header, then we need to read
2382  some packets to get most of the streams, so we cannot
2383  stop here */
2384  if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
2385  /* if we found the info for all the codecs, we can stop */
2386  ret = count;
2387  av_log(ic, AV_LOG_DEBUG, "All info found\n");
2388  break;
2389  }
2390  }
2391  /* we did not get all the codec info, but we read too much data */
2392  if (read_size >= ic->probesize) {
2393  ret = count;
2394  av_log(ic, AV_LOG_DEBUG, "Probe buffer size limit %d reached\n", ic->probesize);
2395  break;
2396  }
2397 
2398  /* NOTE: a new stream can be added there if no header in file
2399  (AVFMTCTX_NOHEADER) */
2400  ret = read_frame_internal(ic, &pkt1);
2401  if (ret == AVERROR(EAGAIN))
2402  continue;
2403 
2404  if (ret < 0) {
2405  /* EOF or error*/
2406  AVPacket empty_pkt = { 0 };
2407  int err;
2408  av_init_packet(&empty_pkt);
2409 
2410  ret = -1; /* we could not have all the codec parameters before EOF */
2411  for(i=0;i<ic->nb_streams;i++) {
2412  st = ic->streams[i];
2413 
2414  /* flush the decoders */
2415  do {
2416  err = try_decode_frame(st, &empty_pkt,
2417  (options && i < orig_nb_streams) ?
2418  &options[i] : NULL);
2419  } while (err > 0 && !has_codec_parameters(st->codec));
2420 
2421  if (err < 0) {
2422  av_log(ic, AV_LOG_WARNING,
2423  "decoding for stream %d failed\n", st->index);
2424  } else if (!has_codec_parameters(st->codec)){
2425  char buf[256];
2426  avcodec_string(buf, sizeof(buf), st->codec, 0);
2427  av_log(ic, AV_LOG_WARNING,
2428  "Could not find codec parameters (%s)\n", buf);
2429  } else {
2430  ret = 0;
2431  }
2432  }
2433  break;
2434  }
2435 
2436  pkt= add_to_pktbuf(&ic->packet_buffer, &pkt1, &ic->packet_buffer_end);
2437  if ((ret = av_dup_packet(pkt)) < 0)
2438  goto find_stream_info_err;
2439 
2440  read_size += pkt->size;
2441 
2442  st = ic->streams[pkt->stream_index];
2443  if (st->codec_info_nb_frames>1) {
2445  av_log(ic, AV_LOG_WARNING, "max_analyze_duration reached\n");
2446  break;
2447  }
2448  st->info->codec_info_duration += pkt->duration;
2449  }
2450  {
2451  int64_t last = st->info->last_dts;
2452 
2453  if(pkt->dts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && pkt->dts > last){
2454  int64_t duration= pkt->dts - last;
2455  double dur= duration * av_q2d(st->time_base);
2456 
2457 // if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2458 // av_log(NULL, AV_LOG_ERROR, "%f\n", dur);
2459  if (st->info->duration_count < 2)
2460  memset(st->info->duration_error, 0, sizeof(st->info->duration_error));
2461  for (i=1; i<FF_ARRAY_ELEMS(st->info->duration_error); i++) {
2462  int framerate= get_std_framerate(i);
2463  int ticks= lrintf(dur*framerate/(1001*12));
2464  double error = dur - (double)ticks*1001*12 / framerate;
2465  st->info->duration_error[i] += error*error;
2466  }
2467  st->info->duration_count++;
2468  // ignore the first 4 values, they might have some random jitter
2469  if (st->info->duration_count > 3)
2470  st->info->duration_gcd = av_gcd(st->info->duration_gcd, duration);
2471  }
2472  if (last == AV_NOPTS_VALUE || st->info->duration_count <= 1)
2473  st->info->last_dts = pkt->dts;
2474  }
2475  if(st->parser && st->parser->parser->split && !st->codec->extradata){
2476  int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
2477  if (i > 0 && i < FF_MAX_EXTRADATA_SIZE) {
2478  st->codec->extradata_size= i;
2480  if (!st->codec->extradata)
2481  return AVERROR(ENOMEM);
2482  memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);
2483  memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2484  }
2485  }
2486 
2487  /* if still no information, we try to open the codec and to
2488  decompress the frame. We try to avoid that in most cases as
2489  it takes longer and uses more memory. For MPEG-4, we need to
2490  decompress for QuickTime.
2491 
2492  If CODEC_CAP_CHANNEL_CONF is set this will force decoding of at
2493  least one frame of codec data, this makes sure the codec initializes
2494  the channel configuration and does not only trust the values from the container.
2495  */
2496  try_decode_frame(st, pkt, (options && i < orig_nb_streams ) ? &options[i] : NULL);
2497 
2498  st->codec_info_nb_frames++;
2499  count++;
2500  }
2501 
2502  // close codecs which were opened in try_decode_frame()
2503  for(i=0;i<ic->nb_streams;i++) {
2504  st = ic->streams[i];
2505  avcodec_close(st->codec);
2506  }
2507  for(i=0;i<ic->nb_streams;i++) {
2508  st = ic->streams[i];
2511  (st->codec_info_nb_frames-2)*(int64_t)st->time_base.den,
2512  st->info->codec_info_duration*(int64_t)st->time_base.num, 60000);
2513  if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2514  // the check for tb_unreliable() is not completely correct, since this is not about handling
2515  // a unreliable/inexact time base, but a time base that is finer than necessary, as e.g.
2516  // ipmovie.c produces.
2517  if (tb_unreliable(st->codec) && st->info->duration_count > 15 && st->info->duration_gcd > 1 && !st->r_frame_rate.num)
2518  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);
2519  if (st->info->duration_count && !st->r_frame_rate.num
2520  && tb_unreliable(st->codec) /*&&
2521  //FIXME we should not special-case MPEG-2, but this needs testing with non-MPEG-2 ...
2522  st->time_base.num*duration_sum[i]/st->info->duration_count*101LL > st->time_base.den*/){
2523  int num = 0;
2524  double best_error= 2*av_q2d(st->time_base);
2525  best_error = best_error*best_error*st->info->duration_count*1000*12*30;
2526 
2527  for (j=1; j<FF_ARRAY_ELEMS(st->info->duration_error); j++) {
2528  double error = st->info->duration_error[j] * get_std_framerate(j);
2529 // if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2530 // av_log(NULL, AV_LOG_ERROR, "%f %f\n", get_std_framerate(j) / 12.0/1001, error);
2531  if(error < best_error){
2532  best_error= error;
2533  num = get_std_framerate(j);
2534  }
2535  }
2536  // do not increase frame rate by more than 1 % in order to match a standard rate.
2537  if (num && (!st->r_frame_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(st->r_frame_rate)))
2538  av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX);
2539  }
2540 
2541  if (!st->r_frame_rate.num){
2542  if( st->codec->time_base.den * (int64_t)st->time_base.num
2543  <= st->codec->time_base.num * st->codec->ticks_per_frame * (int64_t)st->time_base.den){
2544  st->r_frame_rate.num = st->codec->time_base.den;
2546  }else{
2547  st->r_frame_rate.num = st->time_base.den;
2548  st->r_frame_rate.den = st->time_base.num;
2549  }
2550  }
2551  }else if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2552  if(!st->codec->bits_per_coded_sample)
2554  // set stream disposition based on audio service type
2555  switch (st->codec->audio_service_type) {
2563  st->disposition = AV_DISPOSITION_COMMENT; break;
2565  st->disposition = AV_DISPOSITION_KARAOKE; break;
2566  }
2567  }
2568  }
2569 
2570  estimate_timings(ic, old_offset);
2571 
2573 
2574 #if 0
2575  /* correct DTS for B-frame streams with no timestamps */
2576  for(i=0;i<ic->nb_streams;i++) {
2577  st = ic->streams[i];
2578  if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2579  if(b-frames){
2580  ppktl = &ic->packet_buffer;
2581  while(ppkt1){
2582  if(ppkt1->stream_index != i)
2583  continue;
2584  if(ppkt1->pkt->dts < 0)
2585  break;
2586  if(ppkt1->pkt->pts != AV_NOPTS_VALUE)
2587  break;
2588  ppkt1->pkt->dts -= delta;
2589  ppkt1= ppkt1->next;
2590  }
2591  if(ppkt1)
2592  continue;
2593  st->cur_dts -= delta;
2594  }
2595  }
2596  }
2597 #endif
2598 
2599  find_stream_info_err:
2600  for (i=0; i < ic->nb_streams; i++) {
2601  if (ic->streams[i]->codec)
2602  ic->streams[i]->codec->thread_count = 0;
2603  av_freep(&ic->streams[i]->info);
2604  }
2605  return ret;
2606 }
2607 
2609 {
2610  int i, j;
2611 
2612  for (i = 0; i < ic->nb_programs; i++)
2613  for (j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
2614  if (ic->programs[i]->stream_index[j] == s)
2615  return ic->programs[i];
2616  return NULL;
2617 }
2618 
2620  enum AVMediaType type,
2621  int wanted_stream_nb,
2622  int related_stream,
2623  AVCodec **decoder_ret,
2624  int flags)
2625 {
2626  int i, nb_streams = ic->nb_streams;
2627  int ret = AVERROR_STREAM_NOT_FOUND, best_count = -1;
2628  unsigned *program = NULL;
2629  AVCodec *decoder = NULL, *best_decoder = NULL;
2630 
2631  if (related_stream >= 0 && wanted_stream_nb < 0) {
2632  AVProgram *p = find_program_from_stream(ic, related_stream);
2633  if (p) {
2634  program = p->stream_index;
2635  nb_streams = p->nb_stream_indexes;
2636  }
2637  }
2638  for (i = 0; i < nb_streams; i++) {
2639  int real_stream_index = program ? program[i] : i;
2640  AVStream *st = ic->streams[real_stream_index];
2641  AVCodecContext *avctx = st->codec;
2642  if (avctx->codec_type != type)
2643  continue;
2644  if (wanted_stream_nb >= 0 && real_stream_index != wanted_stream_nb)
2645  continue;
2647  continue;
2648  if (decoder_ret) {
2649  decoder = avcodec_find_decoder(st->codec->codec_id);
2650  if (!decoder) {
2651  if (ret < 0)
2653  continue;
2654  }
2655  }
2656  if (best_count >= st->codec_info_nb_frames)
2657  continue;
2658  best_count = st->codec_info_nb_frames;
2659  ret = real_stream_index;
2660  best_decoder = decoder;
2661  if (program && i == nb_streams - 1 && ret < 0) {
2662  program = NULL;
2663  nb_streams = ic->nb_streams;
2664  i = 0; /* no related stream found, try again with everything */
2665  }
2666  }
2667  if (decoder_ret)
2668  *decoder_ret = best_decoder;
2669  return ret;
2670 }
2671 
2672 /*******************************************************/
2673 
2675 {
2676  if (s->iformat->read_play)
2677  return s->iformat->read_play(s);
2678  if (s->pb)
2679  return avio_pause(s->pb, 0);
2680  return AVERROR(ENOSYS);
2681 }
2682 
2684 {
2685  if (s->iformat->read_pause)
2686  return s->iformat->read_pause(s);
2687  if (s->pb)
2688  return avio_pause(s->pb, 1);
2689  return AVERROR(ENOSYS);
2690 }
2691 
2692 #if FF_API_FORMAT_PARAMETERS
2693 void av_close_input_stream(AVFormatContext *s)
2694 {
2695  flush_packet_queue(s);
2696  if (s->iformat->read_close)
2697  s->iformat->read_close(s);
2699 }
2700 #endif
2701 
2703 {
2704  int i;
2705  AVStream *st;
2706 
2707  av_opt_free(s);
2708  if (s->iformat && s->iformat->priv_class && s->priv_data)
2709  av_opt_free(s->priv_data);
2710 
2711  for(i=0;i<s->nb_streams;i++) {
2712  /* free all data in a stream component */
2713  st = s->streams[i];
2714  if (st->parser) {
2715  av_parser_close(st->parser);
2716  av_free_packet(&st->cur_pkt);
2717  }
2718  av_dict_free(&st->metadata);
2719  av_freep(&st->probe_data.buf);
2720  av_free(st->index_entries);
2721  av_free(st->codec->extradata);
2723  av_free(st->codec);
2724  av_free(st->priv_data);
2725  av_free(st->info);
2726  av_free(st);
2727  }
2728  for(i=s->nb_programs-1; i>=0; i--) {
2729  av_dict_free(&s->programs[i]->metadata);
2730  av_freep(&s->programs[i]->stream_index);
2731  av_freep(&s->programs[i]);
2732  }
2733  av_freep(&s->programs);
2734  av_freep(&s->priv_data);
2735  while(s->nb_chapters--) {
2737  av_free(s->chapters[s->nb_chapters]);
2738  }
2739  av_freep(&s->chapters);
2740  av_dict_free(&s->metadata);
2741  av_freep(&s->streams);
2742  av_free(s);
2743 }
2744 
2745 #if FF_API_CLOSE_INPUT_FILE
2746 void av_close_input_file(AVFormatContext *s)
2747 {
2749 }
2750 #endif
2751 
2753 {
2754  AVFormatContext *s = *ps;
2756  NULL : s->pb;
2757  flush_packet_queue(s);
2758  if (s->iformat->read_close)
2759  s->iformat->read_close(s);
2761  *ps = NULL;
2762  if (pb)
2763  avio_close(pb);
2764 }
2765 
2766 #if FF_API_NEW_STREAM
2767 AVStream *av_new_stream(AVFormatContext *s, int id)
2768 {
2769  AVStream *st = avformat_new_stream(s, NULL);
2770  if (st)
2771  st->id = id;
2772  return st;
2773 }
2774 #endif
2775 
2777 {
2778  AVStream *st;
2779  int i;
2780  AVStream **streams;
2781 
2782  if (s->nb_streams >= INT_MAX/sizeof(*streams))
2783  return NULL;
2784  streams = av_realloc(s->streams, (s->nb_streams + 1) * sizeof(*streams));
2785  if (!streams)
2786  return NULL;
2787  s->streams = streams;
2788 
2789  st = av_mallocz(sizeof(AVStream));
2790  if (!st)
2791  return NULL;
2792  if (!(st->info = av_mallocz(sizeof(*st->info)))) {
2793  av_free(st);
2794  return NULL;
2795  }
2796 
2797  st->codec = avcodec_alloc_context3(c);
2798  if (s->iformat) {
2799  /* no default bitrate if decoding */
2800  st->codec->bit_rate = 0;
2801  }
2802  st->index = s->nb_streams;
2803  st->start_time = AV_NOPTS_VALUE;
2804  st->duration = AV_NOPTS_VALUE;
2805  /* we set the current DTS to 0 so that formats without any timestamps
2806  but durations get some timestamps, formats with some unknown
2807  timestamps have their first few packets buffered and the
2808  timestamps corrected before they are returned to the user */
2809  st->cur_dts = 0;
2810  st->first_dts = AV_NOPTS_VALUE;
2812 
2813  /* default pts setting is MPEG-like */
2814  avpriv_set_pts_info(st, 33, 1, 90000);
2816  for(i=0; i<MAX_REORDER_DELAY+1; i++)
2817  st->pts_buffer[i]= AV_NOPTS_VALUE;
2819 
2820  st->sample_aspect_ratio = (AVRational){0,1};
2821 
2822  s->streams[s->nb_streams++] = st;
2823  return st;
2824 }
2825 
2827 {
2828  AVProgram *program=NULL;
2829  int i;
2830 
2831  av_dlog(ac, "new_program: id=0x%04x\n", id);
2832 
2833  for(i=0; i<ac->nb_programs; i++)
2834  if(ac->programs[i]->id == id)
2835  program = ac->programs[i];
2836 
2837  if(!program){
2838  program = av_mallocz(sizeof(AVProgram));
2839  if (!program)
2840  return NULL;
2841  dynarray_add(&ac->programs, &ac->nb_programs, program);
2842  program->discard = AVDISCARD_NONE;
2843  }
2844  program->id = id;
2845 
2846  return program;
2847 }
2848 
2849 AVChapter *avpriv_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title)
2850 {
2851  AVChapter *chapter = NULL;
2852  int i;
2853 
2854  for(i=0; i<s->nb_chapters; i++)
2855  if(s->chapters[i]->id == id)
2856  chapter = s->chapters[i];
2857 
2858  if(!chapter){
2859  chapter= av_mallocz(sizeof(AVChapter));
2860  if(!chapter)
2861  return NULL;
2862  dynarray_add(&s->chapters, &s->nb_chapters, chapter);
2863  }
2864  av_dict_set(&chapter->metadata, "title", title, 0);
2865  chapter->id = id;
2866  chapter->time_base= time_base;
2867  chapter->start = start;
2868  chapter->end = end;
2869 
2870  return chapter;
2871 }
2872 
2873 /************************************************************/
2874 /* output media file */
2875 
2876 #if FF_API_FORMAT_PARAMETERS
2877 int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
2878 {
2879  int ret;
2880 
2881  if (s->oformat->priv_data_size > 0) {
2883  if (!s->priv_data)
2884  return AVERROR(ENOMEM);
2885  if (s->oformat->priv_class) {
2886  *(const AVClass**)s->priv_data= s->oformat->priv_class;
2888  }
2889  } else
2890  s->priv_data = NULL;
2891 
2892  if (s->oformat->set_parameters) {
2893  ret = s->oformat->set_parameters(s, ap);
2894  if (ret < 0)
2895  return ret;
2896  }
2897  return 0;
2898 }
2899 #endif
2900 
2902 {
2903  const AVCodecTag *avctag;
2904  int n;
2905  enum CodecID id = CODEC_ID_NONE;
2906  unsigned int tag = 0;
2907 
2914  for (n = 0; s->oformat->codec_tag[n]; n++) {
2915  avctag = s->oformat->codec_tag[n];
2916  while (avctag->id != CODEC_ID_NONE) {
2917  if (avpriv_toupper4(avctag->tag) == avpriv_toupper4(st->codec->codec_tag)) {
2918  id = avctag->id;
2919  if (id == st->codec->codec_id)
2920  return 1;
2921  }
2922  if (avctag->id == st->codec->codec_id)
2923  tag = avctag->tag;
2924  avctag++;
2925  }
2926  }
2927  if (id != CODEC_ID_NONE)
2928  return 0;
2929  if (tag && (st->codec->strict_std_compliance >= FF_COMPLIANCE_NORMAL))
2930  return 0;
2931  return 1;
2932 }
2933 
2934 #if FF_API_FORMAT_PARAMETERS
2935 int av_write_header(AVFormatContext *s)
2936 {
2937  return avformat_write_header(s, NULL);
2938 }
2939 #endif
2940 
2942 {
2943  int ret = 0, i;
2944  AVStream *st;
2945  AVDictionary *tmp = NULL;
2946 
2947  if (options)
2948  av_dict_copy(&tmp, *options, 0);
2949  if ((ret = av_opt_set_dict(s, &tmp)) < 0)
2950  goto fail;
2951 
2952  // some sanity checks
2953  if (s->nb_streams == 0 && !(s->oformat->flags & AVFMT_NOSTREAMS)) {
2954  av_log(s, AV_LOG_ERROR, "no streams\n");
2955  ret = AVERROR(EINVAL);
2956  goto fail;
2957  }
2958 
2959  for(i=0;i<s->nb_streams;i++) {
2960  st = s->streams[i];
2961 
2962  switch (st->codec->codec_type) {
2963  case AVMEDIA_TYPE_AUDIO:
2964  if(st->codec->sample_rate<=0){
2965  av_log(s, AV_LOG_ERROR, "sample rate not set\n");
2966  ret = AVERROR(EINVAL);
2967  goto fail;
2968  }
2969  if(!st->codec->block_align)
2970  st->codec->block_align = st->codec->channels *
2972  break;
2973  case AVMEDIA_TYPE_VIDEO:
2974  if(st->codec->time_base.num<=0 || st->codec->time_base.den<=0){ //FIXME audio too?
2975  av_log(s, AV_LOG_ERROR, "time base not set\n");
2976  ret = AVERROR(EINVAL);
2977  goto fail;
2978  }
2979  if((st->codec->width<=0 || st->codec->height<=0) && !(s->oformat->flags & AVFMT_NODIMENSIONS)){
2980  av_log(s, AV_LOG_ERROR, "dimensions not set\n");
2981  ret = AVERROR(EINVAL);
2982  goto fail;
2983  }
2985  av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between encoder and muxer layer\n");
2986  ret = AVERROR(EINVAL);
2987  goto fail;
2988  }
2989  break;
2990  }
2991 
2992  if(s->oformat->codec_tag){
2994  //the current rawvideo encoding system ends up setting the wrong codec_tag for avi, we override it here
2995  st->codec->codec_tag= 0;
2996  }
2997  if(st->codec->codec_tag){
2998  if (!validate_codec_tag(s, st)) {
2999  char tagbuf[32];
3000  av_get_codec_tag_string(tagbuf, sizeof(tagbuf), st->codec->codec_tag);
3001  av_log(s, AV_LOG_ERROR,
3002  "Tag %s/0x%08x incompatible with output codec id '%d'\n",
3003  tagbuf, st->codec->codec_tag, st->codec->codec_id);
3004  ret = AVERROR_INVALIDDATA;
3005  goto fail;
3006  }
3007  }else
3009  }
3010 
3011  if(s->oformat->flags & AVFMT_GLOBALHEADER &&
3013  av_log(s, AV_LOG_WARNING, "Codec for stream %d does not use global headers but container format requires global headers\n", i);
3014  }
3015 
3016  if (!s->priv_data && s->oformat->priv_data_size > 0) {
3018  if (!s->priv_data) {
3019  ret = AVERROR(ENOMEM);
3020  goto fail;
3021  }
3022  if (s->oformat->priv_class) {
3023  *(const AVClass**)s->priv_data= s->oformat->priv_class;
3025  if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
3026  goto fail;
3027  }
3028  }
3029 
3030  /* set muxer identification string */
3031  if (s->nb_streams && !(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
3032  av_dict_set(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
3033  }
3034 
3035  if(s->oformat->write_header){
3036  ret = s->oformat->write_header(s);
3037  if (ret < 0)
3038  goto fail;
3039  }
3040 
3041  /* init PTS generation */
3042  for(i=0;i<s->nb_streams;i++) {
3043  int64_t den = AV_NOPTS_VALUE;
3044  st = s->streams[i];
3045 
3046  switch (st->codec->codec_type) {
3047  case AVMEDIA_TYPE_AUDIO:
3048  den = (int64_t)st->time_base.num * st->codec->sample_rate;
3049  break;
3050  case AVMEDIA_TYPE_VIDEO:
3051  den = (int64_t)st->time_base.num * st->codec->time_base.den;
3052  break;
3053  default:
3054  break;
3055  }
3056  if (den != AV_NOPTS_VALUE) {
3057  if (den <= 0) {
3058  ret = AVERROR_INVALIDDATA;
3059  goto fail;
3060  }
3061  frac_init(&st->pts, 0, 0, den);
3062  }
3063  }
3064 
3065  if (options) {
3066  av_dict_free(options);
3067  *options = tmp;
3068  }
3069  return 0;
3070 fail:
3071  av_dict_free(&tmp);
3072  return ret;
3073 }
3074 
3075 //FIXME merge with compute_pkt_fields
3077  int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);
3078  int num, den, frame_size, i;
3079 
3080  av_dlog(s, "compute_pkt_fields2: pts:%"PRId64" dts:%"PRId64" cur_dts:%"PRId64" b:%d size:%d st:%d\n",
3081  pkt->pts, pkt->dts, st->cur_dts, delay, pkt->size, pkt->stream_index);
3082 
3083 /* if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
3084  return AVERROR(EINVAL);*/
3085 
3086  /* duration field */
3087  if (pkt->duration == 0) {
3088  compute_frame_duration(&num, &den, st, NULL, pkt);
3089  if (den && num) {
3090  pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
3091  }
3092  }
3093 
3094  if(pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay==0)
3095  pkt->pts= pkt->dts;
3096 
3097  //XXX/FIXME this is a temporary hack until all encoders output pts
3098  if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay){
3099  pkt->dts=
3100 // pkt->pts= st->cur_dts;
3101  pkt->pts= st->pts.val;
3102  }
3103 
3104  //calculate dts from pts
3105  if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
3106  st->pts_buffer[0]= pkt->pts;
3107  for(i=1; i<delay+1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
3108  st->pts_buffer[i]= pkt->pts + (i-delay-1) * pkt->duration;
3109  for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
3110  FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
3111 
3112  pkt->dts= st->pts_buffer[0];
3113  }
3114 
3115  if(st->cur_dts && st->cur_dts != AV_NOPTS_VALUE && st->cur_dts >= pkt->dts){
3116  av_log(s, AV_LOG_ERROR,
3117  "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %"PRId64" >= %"PRId64"\n",
3118  st->index, st->cur_dts, pkt->dts);
3119  return AVERROR(EINVAL);
3120  }
3121  if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts){
3122  av_log(s, AV_LOG_ERROR, "pts < dts in stream %d\n", st->index);
3123  return AVERROR(EINVAL);
3124  }
3125 
3126 // av_log(s, AV_LOG_DEBUG, "av_write_frame: pts2:%"PRId64" dts2:%"PRId64"\n", pkt->pts, pkt->dts);
3127  st->cur_dts= pkt->dts;
3128  st->pts.val= pkt->dts;
3129 
3130  /* update pts */
3131  switch (st->codec->codec_type) {
3132  case AVMEDIA_TYPE_AUDIO:
3133  frame_size = get_audio_frame_size(st->codec, pkt->size);
3134 
3135  /* HACK/FIXME, we skip the initial 0 size packets as they are most
3136  likely equal to the encoder delay, but it would be better if we
3137  had the real timestamps from the encoder */
3138  if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) {
3139  frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
3140  }
3141  break;
3142  case AVMEDIA_TYPE_VIDEO:
3143  frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
3144  break;
3145  default:
3146  break;
3147  }
3148  return 0;
3149 }
3150 
3152 {
3153  int ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
3154 
3155  if(ret<0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
3156  return ret;
3157 
3158  ret= s->oformat->write_packet(s, pkt);
3159 
3160  if (ret >= 0)
3161  s->streams[pkt->stream_index]->nb_frames++;
3162  return ret;
3163 }
3164 
3166  int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
3167 {
3168  AVPacketList **next_point, *this_pktl;
3169 
3170  this_pktl = av_mallocz(sizeof(AVPacketList));
3171  this_pktl->pkt= *pkt;
3172  pkt->destruct= NULL; // do not free original but only the copy
3173  av_dup_packet(&this_pktl->pkt); // duplicate the packet if it uses non-alloced memory
3174 
3176  next_point = &(s->streams[pkt->stream_index]->last_in_packet_buffer->next);
3177  }else
3178  next_point = &s->packet_buffer;
3179 
3180  if(*next_point){
3181  if(compare(s, &s->packet_buffer_end->pkt, pkt)){
3182  while(!compare(s, &(*next_point)->pkt, pkt)){
3183  next_point= &(*next_point)->next;
3184  }
3185  goto next_non_null;
3186  }else{
3187  next_point = &(s->packet_buffer_end->next);
3188  }
3189  }
3190  assert(!*next_point);
3191 
3192  s->packet_buffer_end= this_pktl;
3193 next_non_null:
3194 
3195  this_pktl->next= *next_point;
3196 
3198  *next_point= this_pktl;
3199 }
3200 
3202 {
3203  AVStream *st = s->streams[ pkt ->stream_index];
3204  AVStream *st2= s->streams[ next->stream_index];
3205  int comp = av_compare_ts(next->dts, st2->time_base, pkt->dts,
3206  st->time_base);
3207 
3208  if (comp == 0)
3209  return pkt->stream_index < next->stream_index;
3210  return comp > 0;
3211 }
3212 
3214  AVPacketList *pktl;
3215  int stream_count=0;
3216  int i;
3217 
3218  if(pkt){
3220  }
3221 
3222  for(i=0; i < s->nb_streams; i++)
3223  stream_count+= !!s->streams[i]->last_in_packet_buffer;
3224 
3225  if(stream_count && (s->nb_streams == stream_count || flush)){
3226  pktl= s->packet_buffer;
3227  *out= pktl->pkt;
3228 
3229  s->packet_buffer= pktl->next;
3230  if(!s->packet_buffer)
3231  s->packet_buffer_end= NULL;
3232 
3233  if(s->streams[out->stream_index]->last_in_packet_buffer == pktl)
3235  av_freep(&pktl);
3236  return 1;
3237  }else{
3238  av_init_packet(out);
3239  return 0;
3240  }
3241 }
3242 
3253  if (s->oformat->interleave_packet) {
3254  int ret = s->oformat->interleave_packet(s, out, in, flush);
3255  if (in)
3256  av_free_packet(in);
3257  return ret;
3258  } else
3259  return av_interleave_packet_per_dts(s, out, in, flush);
3260 }
3261 
3263  AVStream *st= s->streams[ pkt->stream_index];
3264  int ret;
3265 
3266  //FIXME/XXX/HACK drop zero sized packets
3267  if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->size==0)
3268  return 0;
3269 
3270  av_dlog(s, "av_interleaved_write_frame size:%d dts:%"PRId64" pts:%"PRId64"\n",
3271  pkt->size, pkt->dts, pkt->pts);
3272  if((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
3273  return ret;
3274 
3275  if(pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
3276  return AVERROR(EINVAL);
3277 
3278  for(;;){
3279  AVPacket opkt;
3280  int ret= interleave_packet(s, &opkt, pkt, 0);
3281  if(ret<=0) //FIXME cleanup needed for ret<0 ?
3282  return ret;
3283 
3284  ret= s->oformat->write_packet(s, &opkt);
3285  if (ret >= 0)
3286  s->streams[opkt.stream_index]->nb_frames++;
3287 
3288  av_free_packet(&opkt);
3289  pkt= NULL;
3290 
3291  if(ret<0)
3292  return ret;
3293  }
3294 }
3295 
3297 {
3298  int ret, i;
3299 
3300  for(;;){
3301  AVPacket pkt;
3302  ret= interleave_packet(s, &pkt, NULL, 1);
3303  if(ret<0) //FIXME cleanup needed for ret<0 ?
3304  goto fail;
3305  if(!ret)
3306  break;
3307 
3308  ret= s->oformat->write_packet(s, &pkt);
3309  if (ret >= 0)
3310  s->streams[pkt.stream_index]->nb_frames++;
3311 
3312  av_free_packet(&pkt);
3313 
3314  if(ret<0)
3315  goto fail;
3316  }
3317 
3318  if(s->oformat->write_trailer)
3319  ret = s->oformat->write_trailer(s);
3320 fail:
3321  for(i=0;i<s->nb_streams;i++) {
3322  av_freep(&s->streams[i]->priv_data);
3323  av_freep(&s->streams[i]->index_entries);
3324  }
3325  if (s->oformat->priv_class)
3326  av_opt_free(s->priv_data);
3327  av_freep(&s->priv_data);
3328  return ret;
3329 }
3330 
3331 void ff_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx)
3332 {
3333  int i, j;
3334  AVProgram *program=NULL;
3335  void *tmp;
3336 
3337  if (idx >= ac->nb_streams) {
3338  av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
3339  return;
3340  }
3341 
3342  for(i=0; i<ac->nb_programs; i++){
3343  if(ac->programs[i]->id != progid)
3344  continue;
3345  program = ac->programs[i];
3346  for(j=0; j<program->nb_stream_indexes; j++)
3347  if(program->stream_index[j] == idx)
3348  return;
3349 
3350  tmp = av_realloc(program->stream_index, sizeof(unsigned int)*(program->nb_stream_indexes+1));
3351  if(!tmp)
3352  return;
3353  program->stream_index = tmp;
3354  program->stream_index[program->nb_stream_indexes++] = idx;
3355  return;
3356  }
3357 }
3358 
3359 static void print_fps(double d, const char *postfix){
3360  uint64_t v= lrintf(d*100);
3361  if (v% 100 ) av_log(NULL, AV_LOG_INFO, ", %3.2f %s", d, postfix);
3362  else if(v%(100*1000)) av_log(NULL, AV_LOG_INFO, ", %1.0f %s", d, postfix);
3363  else av_log(NULL, AV_LOG_INFO, ", %1.0fk %s", d/1000, postfix);
3364 }
3365 
3366 static void dump_metadata(void *ctx, AVDictionary *m, const char *indent)
3367 {
3368  if(m && !(m->count == 1 && av_dict_get(m, "language", NULL, 0))){
3370 
3371  av_log(ctx, AV_LOG_INFO, "%sMetadata:\n", indent);
3372  while((tag=av_dict_get(m, "", tag, AV_DICT_IGNORE_SUFFIX))) {
3373  if(strcmp("language", tag->key))
3374  av_log(ctx, AV_LOG_INFO, "%s %-16s: %s\n", indent, tag->key, tag->value);
3375  }
3376  }
3377 }
3378 
3379 /* "user interface" functions */
3380 static void dump_stream_format(AVFormatContext *ic, int i, int index, int is_output)
3381 {
3382  char buf[256];
3383  int flags = (is_output ? ic->oformat->flags : ic->iformat->flags);
3384  AVStream *st = ic->streams[i];
3385  int g = av_gcd(st->time_base.num, st->time_base.den);
3386  AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL, 0);
3387  avcodec_string(buf, sizeof(buf), st->codec, is_output);
3388  av_log(NULL, AV_LOG_INFO, " Stream #%d.%d", index, i);
3389  /* the pid is an important information, so we display it */
3390  /* XXX: add a generic system */
3391  if (flags & AVFMT_SHOW_IDS)
3392  av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
3393  if (lang)
3394  av_log(NULL, AV_LOG_INFO, "(%s)", lang->value);
3395  av_log(NULL, AV_LOG_DEBUG, ", %d, %d/%d", st->codec_info_nb_frames, st->time_base.num/g, st->time_base.den/g);
3396  av_log(NULL, AV_LOG_INFO, ": %s", buf);
3397  if (st->sample_aspect_ratio.num && // default
3399  AVRational display_aspect_ratio;
3400  av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
3403  1024*1024);
3404  av_log(NULL, AV_LOG_INFO, ", PAR %d:%d DAR %d:%d",
3406  display_aspect_ratio.num, display_aspect_ratio.den);
3407  }
3408  if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO){
3409  if(st->avg_frame_rate.den && st->avg_frame_rate.num)
3410  print_fps(av_q2d(st->avg_frame_rate), "fps");
3411  if(st->r_frame_rate.den && st->r_frame_rate.num)
3412  print_fps(av_q2d(st->r_frame_rate), "tbr");
3413  if(st->time_base.den && st->time_base.num)
3414  print_fps(1/av_q2d(st->time_base), "tbn");
3415  if(st->codec->time_base.den && st->codec->time_base.num)
3416  print_fps(1/av_q2d(st->codec->time_base), "tbc");
3417  }
3419  av_log(NULL, AV_LOG_INFO, " (default)");
3420  if (st->disposition & AV_DISPOSITION_DUB)
3421  av_log(NULL, AV_LOG_INFO, " (dub)");
3423  av_log(NULL, AV_LOG_INFO, " (original)");
3425  av_log(NULL, AV_LOG_INFO, " (comment)");
3427  av_log(NULL, AV_LOG_INFO, " (lyrics)");
3429  av_log(NULL, AV_LOG_INFO, " (karaoke)");
3431  av_log(NULL, AV_LOG_INFO, " (forced)");
3433  av_log(NULL, AV_LOG_INFO, " (hearing impaired)");
3435  av_log(NULL, AV_LOG_INFO, " (visual impaired)");
3437  av_log(NULL, AV_LOG_INFO, " (clean effects)");
3438  av_log(NULL, AV_LOG_INFO, "\n");
3439  dump_metadata(NULL, st->metadata, " ");
3440 }
3441 
3442 #if FF_API_DUMP_FORMAT
3443 void dump_format(AVFormatContext *ic,
3444  int index,
3445  const char *url,
3446  int is_output)
3447 {
3448  av_dump_format(ic, index, url, is_output);
3449 }
3450 #endif
3451 
3453  int index,
3454  const char *url,
3455  int is_output)
3456 {
3457  int i;
3458  uint8_t *printed = ic->nb_streams ? av_mallocz(ic->nb_streams) : NULL;
3459  if (ic->nb_streams && !printed)
3460  return;
3461 
3462  av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",
3463  is_output ? "Output" : "Input",
3464  index,
3465  is_output ? ic->oformat->name : ic->iformat->name,
3466  is_output ? "to" : "from", url);
3467  dump_metadata(NULL, ic->metadata, " ");
3468  if (!is_output) {
3469  av_log(NULL, AV_LOG_INFO, " Duration: ");
3470  if (ic->duration != AV_NOPTS_VALUE) {
3471  int hours, mins, secs, us;
3472  secs = ic->duration / AV_TIME_BASE;
3473  us = ic->duration % AV_TIME_BASE;
3474  mins = secs / 60;
3475  secs %= 60;
3476  hours = mins / 60;
3477  mins %= 60;
3478  av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%02d", hours, mins, secs,
3479  (100 * us) / AV_TIME_BASE);
3480  } else {
3481  av_log(NULL, AV_LOG_INFO, "N/A");
3482  }
3483  if (ic->start_time != AV_NOPTS_VALUE) {
3484  int secs, us;
3485  av_log(NULL, AV_LOG_INFO, ", start: ");
3486  secs = ic->start_time / AV_TIME_BASE;
3487  us = abs(ic->start_time % AV_TIME_BASE);
3488  av_log(NULL, AV_LOG_INFO, "%d.%06d",
3489  secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));
3490  }
3491  av_log(NULL, AV_LOG_INFO, ", bitrate: ");
3492  if (ic->bit_rate) {
3493  av_log(NULL, AV_LOG_INFO,"%d kb/s", ic->bit_rate / 1000);
3494  } else {
3495  av_log(NULL, AV_LOG_INFO, "N/A");
3496  }
3497  av_log(NULL, AV_LOG_INFO, "\n");
3498  }
3499  for (i = 0; i < ic->nb_chapters; i++) {
3500  AVChapter *ch = ic->chapters[i];
3501  av_log(NULL, AV_LOG_INFO, " Chapter #%d.%d: ", index, i);
3502  av_log(NULL, AV_LOG_INFO, "start %f, ", ch->start * av_q2d(ch->time_base));
3503  av_log(NULL, AV_LOG_INFO, "end %f\n", ch->end * av_q2d(ch->time_base));
3504 
3505  dump_metadata(NULL, ch->metadata, " ");
3506  }
3507  if(ic->nb_programs) {
3508  int j, k, total = 0;
3509  for(j=0; j<ic->nb_programs; j++) {
3511  "name", NULL, 0);
3512  av_log(NULL, AV_LOG_INFO, " Program %d %s\n", ic->programs[j]->id,
3513  name ? name->value : "");
3514  dump_metadata(NULL, ic->programs[j]->metadata, " ");
3515  for(k=0; k<ic->programs[j]->nb_stream_indexes; k++) {
3516  dump_stream_format(ic, ic->programs[j]->stream_index[k], index, is_output);
3517  printed[ic->programs[j]->stream_index[k]] = 1;
3518  }
3519  total += ic->programs[j]->nb_stream_indexes;
3520  }
3521  if (total < ic->nb_streams)
3522  av_log(NULL, AV_LOG_INFO, " No Program\n");
3523  }
3524  for(i=0;i<ic->nb_streams;i++)
3525  if (!printed[i])
3526  dump_stream_format(ic, i, index, is_output);
3527 
3528  av_free(printed);
3529 }
3530 
3531 int64_t av_gettime(void)
3532 {
3533  struct timeval tv;
3534  gettimeofday(&tv,NULL);
3535  return (int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
3536 }
3537 
3538 uint64_t ff_ntp_time(void)
3539 {
3540  return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US;
3541 }
3542 
3543 #if FF_API_PARSE_DATE
3544 #include "libavutil/parseutils.h"
3545 
3546 int64_t parse_date(const char *timestr, int duration)
3547 {
3548  int64_t timeval;
3549  av_parse_time(&timeval, timestr, duration);
3550  return timeval;
3551 }
3552 #endif
3553 
3554 #if FF_API_FIND_INFO_TAG
3555 #include "libavutil/parseutils.h"
3556 
3557 int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
3558 {
3559  return av_find_info_tag(arg, arg_size, tag1, info);
3560 }
3561 #endif
3562 
3563 int av_get_frame_filename(char *buf, int buf_size,
3564  const char *path, int number)
3565 {
3566  const char *p;
3567  char *q, buf1[20], c;
3568  int nd, len, percentd_found;
3569 
3570  q = buf;
3571  p = path;
3572  percentd_found = 0;
3573  for(;;) {
3574  c = *p++;
3575  if (c == '\0')
3576  break;
3577  if (c == '%') {
3578  do {
3579  nd = 0;
3580  while (isdigit(*p)) {
3581  nd = nd * 10 + *p++ - '0';
3582  }
3583  c = *p++;
3584  } while (isdigit(c));
3585 
3586  switch(c) {
3587  case '%':
3588  goto addchar;
3589  case 'd':
3590  if (percentd_found)
3591  goto fail;
3592  percentd_found = 1;
3593  snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
3594  len = strlen(buf1);
3595  if ((q - buf + len) > buf_size - 1)
3596  goto fail;
3597  memcpy(q, buf1, len);
3598  q += len;
3599  break;
3600  default:
3601  goto fail;
3602  }
3603  } else {
3604  addchar:
3605  if ((q - buf) < buf_size - 1)
3606  *q++ = c;
3607  }
3608  }
3609  if (!percentd_found)
3610  goto fail;
3611  *q = '\0';
3612  return 0;
3613  fail:
3614  *q = '\0';
3615  return -1;
3616 }
3617 
3618 static void hex_dump_internal(void *avcl, FILE *f, int level, uint8_t *buf, int size)
3619 {
3620  int len, i, j, c;
3621 #undef fprintf
3622 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3623 
3624  for(i=0;i<size;i+=16) {
3625  len = size - i;
3626  if (len > 16)
3627  len = 16;
3628  PRINT("%08x ", i);
3629  for(j=0;j<16;j++) {
3630  if (j < len)
3631  PRINT(" %02x", buf[i+j]);
3632  else
3633  PRINT(" ");
3634  }
3635  PRINT(" ");
3636  for(j=0;j<len;j++) {
3637  c = buf[i+j];
3638  if (c < ' ' || c > '~')
3639  c = '.';
3640  PRINT("%c", c);
3641  }
3642  PRINT("\n");
3643  }
3644 #undef PRINT
3645 }
3646 
3647 void av_hex_dump(FILE *f, uint8_t *buf, int size)
3648 {
3649  hex_dump_internal(NULL, f, 0, buf, size);
3650 }
3651 
3652 void av_hex_dump_log(void *avcl, int level, uint8_t *buf, int size)
3653 {
3654  hex_dump_internal(avcl, NULL, level, buf, size);
3655 }
3656 
3657 static void pkt_dump_internal(void *avcl, FILE *f, int level, AVPacket *pkt, int dump_payload, AVRational time_base)
3658 {
3659 #undef fprintf
3660 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3661  PRINT("stream #%d:\n", pkt->stream_index);
3662  PRINT(" keyframe=%d\n", ((pkt->flags & AV_PKT_FLAG_KEY) != 0));
3663  PRINT(" duration=%0.3f\n", pkt->duration * av_q2d(time_base));
3664  /* DTS is _always_ valid after av_read_frame() */
3665  PRINT(" dts=");
3666  if (pkt->dts == AV_NOPTS_VALUE)
3667  PRINT("N/A");
3668  else
3669  PRINT("%0.3f", pkt->dts * av_q2d(time_base));
3670  /* PTS may not be known if B-frames are present. */
3671  PRINT(" pts=");
3672  if (pkt->pts == AV_NOPTS_VALUE)
3673  PRINT("N/A");
3674  else
3675  PRINT("%0.3f", pkt->pts * av_q2d(time_base));
3676  PRINT("\n");
3677  PRINT(" size=%d\n", pkt->size);
3678 #undef PRINT
3679  if (dump_payload)
3680  av_hex_dump(f, pkt->data, pkt->size);
3681 }
3682 
3683 #if FF_API_PKT_DUMP
3684 void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload)
3685 {
3686  AVRational tb = { 1, AV_TIME_BASE };
3687  pkt_dump_internal(NULL, f, 0, pkt, dump_payload, tb);
3688 }
3689 #endif
3690 
3691 void av_pkt_dump2(FILE *f, AVPacket *pkt, int dump_payload, AVStream *st)
3692 {
3693  pkt_dump_internal(NULL, f, 0, pkt, dump_payload, st->time_base);
3694 }
3695 
3696 #if FF_API_PKT_DUMP
3697 void av_pkt_dump_log(void *avcl, int level, AVPacket *pkt, int dump_payload)
3698 {
3699  AVRational tb = { 1, AV_TIME_BASE };
3700  pkt_dump_internal(avcl, NULL, level, pkt, dump_payload, tb);
3701 }
3702 #endif
3703 
3704 void av_pkt_dump_log2(void *avcl, int level, AVPacket *pkt, int dump_payload,
3705  AVStream *st)
3706 {
3707  pkt_dump_internal(avcl, NULL, level, pkt, dump_payload, st->time_base);
3708 }
3709 
3710 void av_url_split(char *proto, int proto_size,
3711  char *authorization, int authorization_size,
3712  char *hostname, int hostname_size,
3713  int *port_ptr,
3714  char *path, int path_size,
3715  const char *url)
3716 {
3717  const char *p, *ls, *at, *col, *brk;
3718 
3719  if (port_ptr) *port_ptr = -1;
3720  if (proto_size > 0) proto[0] = 0;
3721  if (authorization_size > 0) authorization[0] = 0;
3722  if (hostname_size > 0) hostname[0] = 0;
3723  if (path_size > 0) path[0] = 0;
3724 
3725  /* parse protocol */
3726  if ((p = strchr(url, ':'))) {
3727  av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
3728  p++; /* skip ':' */
3729  if (*p == '/') p++;
3730  if (*p == '/') p++;
3731  } else {
3732  /* no protocol means plain filename */
3733  av_strlcpy(path, url, path_size);
3734  return;
3735  }
3736 
3737  /* separate path from hostname */
3738  ls = strchr(p, '/');
3739  if(!ls)
3740  ls = strchr(p, '?');
3741  if(ls)
3742  av_strlcpy(path, ls, path_size);
3743  else
3744  ls = &p[strlen(p)]; // XXX
3745 
3746  /* the rest is hostname, use that to parse auth/port */
3747  if (ls != p) {
3748  /* authorization (user[:pass]@hostname) */
3749  if ((at = strchr(p, '@')) && at < ls) {
3750  av_strlcpy(authorization, p,
3751  FFMIN(authorization_size, at + 1 - p));
3752  p = at + 1; /* skip '@' */
3753  }
3754 
3755  if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
3756  /* [host]:port */
3757  av_strlcpy(hostname, p + 1,
3758  FFMIN(hostname_size, brk - p));
3759  if (brk[1] == ':' && port_ptr)
3760  *port_ptr = atoi(brk + 2);
3761  } else if ((col = strchr(p, ':')) && col < ls) {
3762  av_strlcpy(hostname, p,
3763  FFMIN(col + 1 - p, hostname_size));
3764  if (port_ptr) *port_ptr = atoi(col + 1);
3765  } else
3766  av_strlcpy(hostname, p,
3767  FFMIN(ls + 1 - p, hostname_size));
3768  }
3769 }
3770 
3771 char *ff_data_to_hex(char *buff, const uint8_t *src, int s, int lowercase)
3772 {
3773  int i;
3774  static const char hex_table_uc[16] = { '0', '1', '2', '3',
3775  '4', '5', '6', '7',
3776  '8', '9', 'A', 'B',
3777  'C', 'D', 'E', 'F' };
3778  static const char hex_table_lc[16] = { '0', '1', '2', '3',
3779  '4', '5', '6', '7',
3780  '8', '9', 'a', 'b',
3781  'c', 'd', 'e', 'f' };
3782  const char *hex_table = lowercase ? hex_table_lc : hex_table_uc;
3783 
3784  for(i = 0; i < s; i++) {
3785  buff[i * 2] = hex_table[src[i] >> 4];
3786  buff[i * 2 + 1] = hex_table[src[i] & 0xF];
3787  }
3788 
3789  return buff;
3790 }
3791 
3792 int ff_hex_to_data(uint8_t *data, const char *p)
3793 {
3794  int c, len, v;
3795 
3796  len = 0;
3797  v = 1;
3798  for (;;) {
3799  p += strspn(p, SPACE_CHARS);
3800  if (*p == '\0')
3801  break;
3802  c = toupper((unsigned char) *p++);
3803  if (c >= '0' && c <= '9')
3804  c = c - '0';
3805  else if (c >= 'A' && c <= 'F')
3806  c = c - 'A' + 10;
3807  else
3808  break;
3809  v = (v << 4) | c;
3810  if (v & 0x100) {
3811  if (data)
3812  data[len] = v;
3813  len++;
3814  v = 1;
3815  }
3816  }
3817  return len;
3818 }
3819 
3820 #if FF_API_SET_PTS_INFO
3821 void av_set_pts_info(AVStream *s, int pts_wrap_bits,
3822  unsigned int pts_num, unsigned int pts_den)
3823 {
3824  avpriv_set_pts_info(s, pts_wrap_bits, pts_num, pts_den);
3825 }
3826 #endif
3827 
3828 void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits,
3829  unsigned int pts_num, unsigned int pts_den)
3830 {
3831  AVRational new_tb;
3832  if(av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)){
3833  if(new_tb.num != pts_num)
3834  av_log(NULL, AV_LOG_DEBUG, "st:%d removing common factor %d from timebase\n", s->index, pts_num/new_tb.num);
3835  }else
3836  av_log(NULL, AV_LOG_WARNING, "st:%d has too large timebase, reducing\n", s->index);
3837 
3838  if(new_tb.num <= 0 || new_tb.den <= 0) {
3839  av_log(NULL, AV_LOG_ERROR, "Ignoring attempt to set invalid timebase for st:%d\n", s->index);
3840  return;
3841  }
3842  s->time_base = new_tb;
3843  s->pts_wrap_bits = pts_wrap_bits;
3844 }
3845 
3846 int ff_url_join(char *str, int size, const char *proto,
3847  const char *authorization, const char *hostname,
3848  int port, const char *fmt, ...)
3849 {
3850 #if CONFIG_NETWORK
3851  struct addrinfo hints, *ai;
3852 #endif
3853 
3854  str[0] = '\0';
3855  if (proto)
3856  av_strlcatf(str, size, "%s://", proto);
3857  if (authorization && authorization[0])
3858  av_strlcatf(str, size, "%s@", authorization);
3859 #if CONFIG_NETWORK && defined(AF_INET6)
3860  /* Determine if hostname is a numerical IPv6 address,
3861  * properly escape it within [] in that case. */
3862  memset(&hints, 0, sizeof(hints));
3863  hints.ai_flags = AI_NUMERICHOST;
3864  if (!getaddrinfo(hostname, NULL, &hints, &ai)) {
3865  if (ai->ai_family == AF_INET6) {
3866  av_strlcat(str, "[", size);
3867  av_strlcat(str, hostname, size);
3868  av_strlcat(str, "]", size);
3869  } else {
3870  av_strlcat(str, hostname, size);
3871  }
3872  freeaddrinfo(ai);
3873  } else
3874 #endif
3875  /* Not an IPv6 address, just output the plain string. */
3876  av_strlcat(str, hostname, size);
3877 
3878  if (port >= 0)
3879  av_strlcatf(str, size, ":%d", port);
3880  if (fmt) {
3881  va_list vl;
3882  int len = strlen(str);
3883 
3884  va_start(vl, fmt);
3885  vsnprintf(str + len, size > len ? size - len : 0, fmt, vl);
3886  va_end(vl);
3887  }
3888  return strlen(str);
3889 }
3890 
3891 int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
3892  AVFormatContext *src)
3893 {
3894  AVPacket local_pkt;
3895 
3896  local_pkt = *pkt;
3897  local_pkt.stream_index = dst_stream;
3898  if (pkt->pts != AV_NOPTS_VALUE)
3899  local_pkt.pts = av_rescale_q(pkt->pts,
3900  src->streams[pkt->stream_index]->time_base,
3901  dst->streams[dst_stream]->time_base);
3902  if (pkt->dts != AV_NOPTS_VALUE)
3903  local_pkt.dts = av_rescale_q(pkt->dts,
3904  src->streams[pkt->stream_index]->time_base,
3905  dst->streams[dst_stream]->time_base);
3906  return av_write_frame(dst, &local_pkt);
3907 }
3908 
3909 void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf,
3910  void *context)
3911 {
3912  const char *ptr = str;
3913 
3914  /* Parse key=value pairs. */
3915  for (;;) {
3916  const char *key;
3917  char *dest = NULL, *dest_end;
3918  int key_len, dest_len = 0;
3919 
3920  /* Skip whitespace and potential commas. */
3921  while (*ptr && (isspace(*ptr) || *ptr == ','))
3922  ptr++;
3923  if (!*ptr)
3924  break;
3925 
3926  key = ptr;
3927 
3928  if (!(ptr = strchr(key, '=')))
3929  break;
3930  ptr++;
3931  key_len = ptr - key;
3932 
3933  callback_get_buf(context, key, key_len, &dest, &dest_len);
3934  dest_end = dest + dest_len - 1;
3935 
3936  if (*ptr == '\"') {
3937  ptr++;
3938  while (*ptr && *ptr != '\"') {
3939  if (*ptr == '\\') {
3940  if (!ptr[1])
3941  break;
3942  if (dest && dest < dest_end)
3943  *dest++ = ptr[1];
3944  ptr += 2;
3945  } else {
3946  if (dest && dest < dest_end)
3947  *dest++ = *ptr;
3948  ptr++;
3949  }
3950  }
3951  if (*ptr == '\"')
3952  ptr++;
3953  } else {
3954  for (; *ptr && !(isspace(*ptr) || *ptr == ','); ptr++)
3955  if (dest && dest < dest_end)
3956  *dest++ = *ptr;
3957  }
3958  if (dest)
3959  *dest = 0;
3960  }
3961 }
3962 
3964 {
3965  int i;
3966  for (i = 0; i < s->nb_streams; i++) {
3967  if (s->streams[i]->id == id)
3968  return i;
3969  }
3970  return -1;
3971 }
3972 
3973 void ff_make_absolute_url(char *buf, int size, const char *base,
3974  const char *rel)
3975 {
3976  char *sep;
3977  /* Absolute path, relative to the current server */
3978  if (base && strstr(base, "://") && rel[0] == '/') {
3979  if (base != buf)
3980  av_strlcpy(buf, base, size);
3981  sep = strstr(buf, "://");
3982  if (sep) {
3983  sep += 3;
3984  sep = strchr(sep, '/');
3985  if (sep)
3986  *sep = '\0';
3987  }
3988  av_strlcat(buf, rel, size);
3989  return;
3990  }
3991  /* If rel actually is an absolute url, just copy it */
3992  if (!base || strstr(rel, "://") || rel[0] == '/') {
3993  av_strlcpy(buf, rel, size);
3994  return;
3995  }
3996  if (base != buf)
3997  av_strlcpy(buf, base, size);
3998  /* Remove the file name from the base url */
3999  sep = strrchr(buf, '/');
4000  if (sep)
4001  sep[1] = '\0';
4002  else
4003  buf[0] = '\0';
4004  while (av_strstart(rel, "../", NULL) && sep) {
4005  /* Remove the path delimiter at the end */
4006  sep[0] = '\0';
4007  sep = strrchr(buf, '/');
4008  /* If the next directory name to pop off is "..", break here */
4009  if (!strcmp(sep ? &sep[1] : buf, "..")) {
4010  /* Readd the slash we just removed */
4011  av_strlcat(buf, "/", size);
4012  break;
4013  }
4014  /* Cut off the directory name */
4015  if (sep)
4016  sep[1] = '\0';
4017  else
4018  buf[0] = '\0';
4019  rel += 3;
4020  }
4021  av_strlcat(buf, rel, size);
4022 }
4023 
4024 int64_t ff_iso8601_to_unix_time(const char *datestr)
4025 {
4026 #if HAVE_STRPTIME
4027  struct tm time1 = {0}, time2 = {0};
4028  char *ret1, *ret2;
4029  ret1 = strptime(datestr, "%Y - %m - %d %T", &time1);
4030  ret2 = strptime(datestr, "%Y - %m - %dT%T", &time2);
4031  if (ret2 && !ret1)
4032  return av_timegm(&time2);
4033  else
4034  return av_timegm(&time1);
4035 #else
4036  av_log(NULL, AV_LOG_WARNING, "strptime() unavailable on this system, cannot convert "
4037  "the date string.\n");
4038  return 0;
4039 #endif
4040 }
4041 
4042 int avformat_query_codec(AVOutputFormat *ofmt, enum CodecID codec_id, int std_compliance)
4043 {
4044  if (ofmt) {
4045  if (ofmt->query_codec)
4046  return ofmt->query_codec(codec_id, std_compliance);
4047  else if (ofmt->codec_tag)
4048  return !!av_codec_get_tag(ofmt->codec_tag, codec_id);
4049  else if (codec_id == ofmt->video_codec || codec_id == ofmt->audio_codec ||
4050  codec_id == ofmt->subtitle_codec)
4051  return 1;
4052  }
4053  return AVERROR_PATCHWELCOME;
4054 }
4055 
4057 {
4058 #if CONFIG_NETWORK
4059  int ret;
4061  if ((ret = ff_network_init()) < 0)
4062  return ret;
4063  ff_tls_init();
4064 #endif
4065  return 0;
4066 }
4067 
4069 {
4070 #if CONFIG_NETWORK
4071  ff_network_close();
4072  ff_tls_deinit();
4073 #endif
4074  return 0;
4075 }
4076 
4077 int ff_add_param_change(AVPacket *pkt, int32_t channels,
4078  uint64_t channel_layout, int32_t sample_rate,
4079  int32_t width, int32_t height)
4080 {
4081  uint32_t flags = 0;
4082  int size = 4;
4083  uint8_t *data;
4084  if (!pkt)
4085  return AVERROR(EINVAL);
4086  if (channels) {
4087  size += 4;
4089  }
4090  if (channel_layout) {
4091  size += 8;
4093  }
4094  if (sample_rate) {
4095  size += 4;
4097  }
4098  if (width || height) {
4099  size += 8;
4101  }
4103  if (!data)
4104  return AVERROR(ENOMEM);
4105  bytestream_put_le32(&data, flags);
4106  if (channels)
4107  bytestream_put_le32(&data, channels);
4108  if (channel_layout)
4109  bytestream_put_le64(&data, channel_layout);
4110  if (sample_rate)
4111  bytestream_put_le32(&data, sample_rate);
4112  if (width || height) {
4113  bytestream_put_le32(&data, width);
4114  bytestream_put_le32(&data, height);
4115  }
4116  return 0;
4117 }
4118 
4120 {
4121  return ff_codec_bmp_tags;
4122 }
4124 {
4125  return ff_codec_wav_tags;
4126 }