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.

4311 lines
147KB

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