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