You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4366 lines
148KB

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