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