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.

3152 lines
94KB

  1. /*
  2. * Various utilities for ffmpeg system
  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 "avformat.h"
  22. #include "allformats.h"
  23. #include "opt.h"
  24. #undef NDEBUG
  25. #include <assert.h>
  26. /**
  27. * @file libavformat/utils.c
  28. * Various utility functions for using ffmpeg library.
  29. */
  30. static void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den);
  31. static void av_frac_add(AVFrac *f, int64_t incr);
  32. /** head of registered input format linked list. */
  33. AVInputFormat *first_iformat = NULL;
  34. /** head of registered output format linked list. */
  35. AVOutputFormat *first_oformat = NULL;
  36. void av_register_input_format(AVInputFormat *format)
  37. {
  38. AVInputFormat **p;
  39. p = &first_iformat;
  40. while (*p != NULL) p = &(*p)->next;
  41. *p = format;
  42. format->next = NULL;
  43. }
  44. void av_register_output_format(AVOutputFormat *format)
  45. {
  46. AVOutputFormat **p;
  47. p = &first_oformat;
  48. while (*p != NULL) p = &(*p)->next;
  49. *p = format;
  50. format->next = NULL;
  51. }
  52. int match_ext(const char *filename, const char *extensions)
  53. {
  54. const char *ext, *p;
  55. char ext1[32], *q;
  56. if(!filename)
  57. return 0;
  58. ext = strrchr(filename, '.');
  59. if (ext) {
  60. ext++;
  61. p = extensions;
  62. for(;;) {
  63. q = ext1;
  64. while (*p != '\0' && *p != ',' && q-ext1<sizeof(ext1)-1)
  65. *q++ = *p++;
  66. *q = '\0';
  67. if (!strcasecmp(ext1, ext))
  68. return 1;
  69. if (*p == '\0')
  70. break;
  71. p++;
  72. }
  73. }
  74. return 0;
  75. }
  76. AVOutputFormat *guess_format(const char *short_name, const char *filename,
  77. const char *mime_type)
  78. {
  79. AVOutputFormat *fmt, *fmt_found;
  80. int score_max, score;
  81. /* specific test for image sequences */
  82. #ifdef CONFIG_IMAGE2_MUXER
  83. if (!short_name && filename &&
  84. av_filename_number_test(filename) &&
  85. av_guess_image2_codec(filename) != CODEC_ID_NONE) {
  86. return guess_format("image2", NULL, NULL);
  87. }
  88. #endif
  89. /* find the proper file type */
  90. fmt_found = NULL;
  91. score_max = 0;
  92. fmt = first_oformat;
  93. while (fmt != NULL) {
  94. score = 0;
  95. if (fmt->name && short_name && !strcmp(fmt->name, short_name))
  96. score += 100;
  97. if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
  98. score += 10;
  99. if (filename && fmt->extensions &&
  100. match_ext(filename, fmt->extensions)) {
  101. score += 5;
  102. }
  103. if (score > score_max) {
  104. score_max = score;
  105. fmt_found = fmt;
  106. }
  107. fmt = fmt->next;
  108. }
  109. return fmt_found;
  110. }
  111. AVOutputFormat *guess_stream_format(const char *short_name, const char *filename,
  112. const char *mime_type)
  113. {
  114. AVOutputFormat *fmt = guess_format(short_name, filename, mime_type);
  115. if (fmt) {
  116. AVOutputFormat *stream_fmt;
  117. char stream_format_name[64];
  118. snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
  119. stream_fmt = guess_format(stream_format_name, NULL, NULL);
  120. if (stream_fmt)
  121. fmt = stream_fmt;
  122. }
  123. return fmt;
  124. }
  125. /**
  126. * Guesses the codec id based upon muxer and filename.
  127. */
  128. enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
  129. const char *filename, const char *mime_type, enum CodecType type){
  130. if(type == CODEC_TYPE_VIDEO){
  131. enum CodecID codec_id= CODEC_ID_NONE;
  132. #ifdef CONFIG_IMAGE2_MUXER
  133. if(!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")){
  134. codec_id= av_guess_image2_codec(filename);
  135. }
  136. #endif
  137. if(codec_id == CODEC_ID_NONE)
  138. codec_id= fmt->video_codec;
  139. return codec_id;
  140. }else if(type == CODEC_TYPE_AUDIO)
  141. return fmt->audio_codec;
  142. else
  143. return CODEC_ID_NONE;
  144. }
  145. /**
  146. * finds AVInputFormat based on input format's short name.
  147. */
  148. AVInputFormat *av_find_input_format(const char *short_name)
  149. {
  150. AVInputFormat *fmt;
  151. for(fmt = first_iformat; fmt != NULL; fmt = fmt->next) {
  152. if (!strcmp(fmt->name, short_name))
  153. return fmt;
  154. }
  155. return NULL;
  156. }
  157. /* memory handling */
  158. /**
  159. * Default packet destructor.
  160. */
  161. void av_destruct_packet(AVPacket *pkt)
  162. {
  163. av_free(pkt->data);
  164. pkt->data = NULL; pkt->size = 0;
  165. }
  166. /**
  167. * Allocate the payload of a packet and intialized its fields to default values.
  168. *
  169. * @param pkt packet
  170. * @param size wanted payload size
  171. * @return 0 if OK. AVERROR_xxx otherwise.
  172. */
  173. int av_new_packet(AVPacket *pkt, int size)
  174. {
  175. uint8_t *data;
  176. if((unsigned)size > (unsigned)size + FF_INPUT_BUFFER_PADDING_SIZE)
  177. return AVERROR_NOMEM;
  178. data = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
  179. if (!data)
  180. return AVERROR_NOMEM;
  181. memset(data + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  182. av_init_packet(pkt);
  183. pkt->data = data;
  184. pkt->size = size;
  185. pkt->destruct = av_destruct_packet;
  186. return 0;
  187. }
  188. /**
  189. * Allocate and read the payload of a packet and intialized its fields to default values.
  190. *
  191. * @param pkt packet
  192. * @param size wanted payload size
  193. * @return >0 (read size) if OK. AVERROR_xxx otherwise.
  194. */
  195. int av_get_packet(ByteIOContext *s, AVPacket *pkt, int size)
  196. {
  197. int ret= av_new_packet(pkt, size);
  198. if(ret<0)
  199. return ret;
  200. pkt->pos= url_ftell(s);
  201. ret= get_buffer(s, pkt->data, size);
  202. if(ret<=0)
  203. av_free_packet(pkt);
  204. else
  205. pkt->size= ret;
  206. return ret;
  207. }
  208. /* This is a hack - the packet memory allocation stuff is broken. The
  209. packet is allocated if it was not really allocated */
  210. int av_dup_packet(AVPacket *pkt)
  211. {
  212. if (pkt->destruct != av_destruct_packet) {
  213. uint8_t *data;
  214. /* we duplicate the packet and don't forget to put the padding
  215. again */
  216. if((unsigned)pkt->size > (unsigned)pkt->size + FF_INPUT_BUFFER_PADDING_SIZE)
  217. return AVERROR_NOMEM;
  218. data = av_malloc(pkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
  219. if (!data) {
  220. return AVERROR_NOMEM;
  221. }
  222. memcpy(data, pkt->data, pkt->size);
  223. memset(data + pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  224. pkt->data = data;
  225. pkt->destruct = av_destruct_packet;
  226. }
  227. return 0;
  228. }
  229. /**
  230. * Check whether filename actually is a numbered sequence generator.
  231. *
  232. * @param filename possible numbered sequence string
  233. * @return 1 if a valid numbered sequence string, 0 otherwise.
  234. */
  235. int av_filename_number_test(const char *filename)
  236. {
  237. char buf[1024];
  238. return filename && (av_get_frame_filename(buf, sizeof(buf), filename, 1)>=0);
  239. }
  240. /**
  241. * Guess file format.
  242. *
  243. * @param is_opened whether the file is already opened, determines whether
  244. * demuxers with or without AVFMT_NOFILE are probed
  245. */
  246. AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened)
  247. {
  248. AVInputFormat *fmt1, *fmt;
  249. int score, score_max;
  250. fmt = NULL;
  251. score_max = 0;
  252. for(fmt1 = first_iformat; fmt1 != NULL; fmt1 = fmt1->next) {
  253. if (!is_opened == !(fmt1->flags & AVFMT_NOFILE))
  254. continue;
  255. score = 0;
  256. if (fmt1->read_probe) {
  257. score = fmt1->read_probe(pd);
  258. } else if (fmt1->extensions) {
  259. if (match_ext(pd->filename, fmt1->extensions)) {
  260. score = 50;
  261. }
  262. }
  263. if (score > score_max) {
  264. score_max = score;
  265. fmt = fmt1;
  266. }
  267. }
  268. return fmt;
  269. }
  270. /************************************************************/
  271. /* input media file */
  272. /**
  273. * Open a media file from an IO stream. 'fmt' must be specified.
  274. */
  275. static const char* format_to_name(void* ptr)
  276. {
  277. AVFormatContext* fc = (AVFormatContext*) ptr;
  278. if(fc->iformat) return fc->iformat->name;
  279. else if(fc->oformat) return fc->oformat->name;
  280. else return "NULL";
  281. }
  282. #define OFFSET(x) offsetof(AVFormatContext,x)
  283. #define DEFAULT 0 //should be NAN but it doesnt work as its not a constant in glibc as required by ANSI/ISO C
  284. //these names are too long to be readable
  285. #define E AV_OPT_FLAG_ENCODING_PARAM
  286. #define D AV_OPT_FLAG_DECODING_PARAM
  287. static const AVOption options[]={
  288. {"probesize", NULL, OFFSET(probesize), FF_OPT_TYPE_INT, 32000, 32, INT_MAX, D}, /* 32000 from mpegts.c: 1.0 second at 24Mbit/s */
  289. {"muxrate", "set mux rate", OFFSET(mux_rate), FF_OPT_TYPE_INT, DEFAULT, 0, INT_MAX, E},
  290. {"packetsize", "set packet size", OFFSET(packet_size), FF_OPT_TYPE_INT, DEFAULT, 0, INT_MAX, E},
  291. {"fflags", NULL, OFFSET(flags), FF_OPT_TYPE_FLAGS, DEFAULT, INT_MIN, INT_MAX, D|E, "fflags"},
  292. {"ignidx", "ignore index", 0, FF_OPT_TYPE_CONST, AVFMT_FLAG_IGNIDX, INT_MIN, INT_MAX, D, "fflags"},
  293. {"genpts", "generate pts", 0, FF_OPT_TYPE_CONST, AVFMT_FLAG_GENPTS, INT_MIN, INT_MAX, D, "fflags"},
  294. {"track", " set the track number", OFFSET(track), FF_OPT_TYPE_INT, DEFAULT, 0, INT_MAX, E},
  295. {"year", "set the year", OFFSET(year), FF_OPT_TYPE_INT, DEFAULT, INT_MIN, INT_MAX, E},
  296. {"analyzeduration", NULL, OFFSET(max_analyze_duration), FF_OPT_TYPE_INT, 3*AV_TIME_BASE, 0, INT_MAX, D},
  297. {NULL},
  298. };
  299. #undef E
  300. #undef D
  301. #undef DEFAULT
  302. static const AVClass av_format_context_class = { "AVFormatContext", format_to_name, options };
  303. static void avformat_get_context_defaults(AVFormatContext *s)
  304. {
  305. memset(s, 0, sizeof(AVFormatContext));
  306. s->av_class = &av_format_context_class;
  307. av_opt_set_defaults(s);
  308. }
  309. AVFormatContext *av_alloc_format_context(void)
  310. {
  311. AVFormatContext *ic;
  312. ic = av_malloc(sizeof(AVFormatContext));
  313. if (!ic) return ic;
  314. avformat_get_context_defaults(ic);
  315. ic->av_class = &av_format_context_class;
  316. return ic;
  317. }
  318. /**
  319. * Allocates all the structures needed to read an input stream.
  320. * This does not open the needed codecs for decoding the stream[s].
  321. */
  322. int av_open_input_stream(AVFormatContext **ic_ptr,
  323. ByteIOContext *pb, const char *filename,
  324. AVInputFormat *fmt, AVFormatParameters *ap)
  325. {
  326. int err;
  327. AVFormatContext *ic;
  328. AVFormatParameters default_ap;
  329. if(!ap){
  330. ap=&default_ap;
  331. memset(ap, 0, sizeof(default_ap));
  332. }
  333. if(!ap->prealloced_context)
  334. ic = av_alloc_format_context();
  335. else
  336. ic = *ic_ptr;
  337. if (!ic) {
  338. err = AVERROR_NOMEM;
  339. goto fail;
  340. }
  341. ic->iformat = fmt;
  342. if (pb)
  343. ic->pb = *pb;
  344. ic->duration = AV_NOPTS_VALUE;
  345. ic->start_time = AV_NOPTS_VALUE;
  346. pstrcpy(ic->filename, sizeof(ic->filename), filename);
  347. /* allocate private data */
  348. if (fmt->priv_data_size > 0) {
  349. ic->priv_data = av_mallocz(fmt->priv_data_size);
  350. if (!ic->priv_data) {
  351. err = AVERROR_NOMEM;
  352. goto fail;
  353. }
  354. } else {
  355. ic->priv_data = NULL;
  356. }
  357. err = ic->iformat->read_header(ic, ap);
  358. if (err < 0)
  359. goto fail;
  360. if (pb && !ic->data_offset)
  361. ic->data_offset = url_ftell(&ic->pb);
  362. *ic_ptr = ic;
  363. return 0;
  364. fail:
  365. if (ic) {
  366. av_freep(&ic->priv_data);
  367. }
  368. av_free(ic);
  369. *ic_ptr = NULL;
  370. return err;
  371. }
  372. /** Size of probe buffer, for guessing file type from file contents. */
  373. #define PROBE_BUF_MIN 2048
  374. #define PROBE_BUF_MAX (1<<20)
  375. /**
  376. * Open a media file as input. The codec are not opened. Only the file
  377. * header (if present) is read.
  378. *
  379. * @param ic_ptr the opened media file handle is put here
  380. * @param filename filename to open.
  381. * @param fmt if non NULL, force the file format to use
  382. * @param buf_size optional buffer size (zero if default is OK)
  383. * @param ap additionnal parameters needed when opening the file (NULL if default)
  384. * @return 0 if OK. AVERROR_xxx otherwise.
  385. */
  386. int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
  387. AVInputFormat *fmt,
  388. int buf_size,
  389. AVFormatParameters *ap)
  390. {
  391. int err, must_open_file, file_opened, probe_size;
  392. AVProbeData probe_data, *pd = &probe_data;
  393. ByteIOContext pb1, *pb = &pb1;
  394. file_opened = 0;
  395. pd->filename = "";
  396. if (filename)
  397. pd->filename = filename;
  398. pd->buf = NULL;
  399. pd->buf_size = 0;
  400. if (!fmt) {
  401. /* guess format if no file can be opened */
  402. fmt = av_probe_input_format(pd, 0);
  403. }
  404. /* do not open file if the format does not need it. XXX: specific
  405. hack needed to handle RTSP/TCP */
  406. must_open_file = 1;
  407. if (fmt && (fmt->flags & AVFMT_NOFILE)) {
  408. must_open_file = 0;
  409. pb= NULL; //FIXME this or memset(pb, 0, sizeof(ByteIOContext)); otherwise its uninitalized
  410. }
  411. if (!fmt || must_open_file) {
  412. /* if no file needed do not try to open one */
  413. if (url_fopen(pb, filename, URL_RDONLY) < 0) {
  414. err = AVERROR_IO;
  415. goto fail;
  416. }
  417. file_opened = 1;
  418. if (buf_size > 0) {
  419. url_setbufsize(pb, buf_size);
  420. }
  421. for(probe_size= PROBE_BUF_MIN; probe_size<=PROBE_BUF_MAX && !fmt; probe_size<<=1){
  422. /* read probe data */
  423. pd->buf= av_realloc(pd->buf, probe_size);
  424. pd->buf_size = get_buffer(pb, pd->buf, probe_size);
  425. if (url_fseek(pb, 0, SEEK_SET) == (offset_t)AVERROR(EPIPE)) {
  426. url_fclose(pb);
  427. if (url_fopen(pb, filename, URL_RDONLY) < 0) {
  428. file_opened = 0;
  429. err = AVERROR_IO;
  430. goto fail;
  431. }
  432. }
  433. /* guess file format */
  434. fmt = av_probe_input_format(pd, 1);
  435. }
  436. av_freep(&pd->buf);
  437. }
  438. /* if still no format found, error */
  439. if (!fmt) {
  440. err = AVERROR_NOFMT;
  441. goto fail;
  442. }
  443. /* XXX: suppress this hack for redirectors */
  444. #ifdef CONFIG_NETWORK
  445. if (fmt == &redir_demuxer) {
  446. err = redir_open(ic_ptr, pb);
  447. url_fclose(pb);
  448. return err;
  449. }
  450. #endif
  451. /* check filename in case of an image number is expected */
  452. if (fmt->flags & AVFMT_NEEDNUMBER) {
  453. if (!av_filename_number_test(filename)) {
  454. err = AVERROR_NUMEXPECTED;
  455. goto fail;
  456. }
  457. }
  458. err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap);
  459. if (err)
  460. goto fail;
  461. return 0;
  462. fail:
  463. av_freep(&pd->buf);
  464. if (file_opened)
  465. url_fclose(pb);
  466. *ic_ptr = NULL;
  467. return err;
  468. }
  469. /*******************************************************/
  470. /**
  471. * Read a transport packet from a media file.
  472. *
  473. * This function is absolete and should never be used.
  474. * Use av_read_frame() instead.
  475. *
  476. * @param s media file handle
  477. * @param pkt is filled
  478. * @return 0 if OK. AVERROR_xxx if error.
  479. */
  480. int av_read_packet(AVFormatContext *s, AVPacket *pkt)
  481. {
  482. return s->iformat->read_packet(s, pkt);
  483. }
  484. /**********************************************************/
  485. /**
  486. * Get the number of samples of an audio frame. Return (-1) if error.
  487. */
  488. static int get_audio_frame_size(AVCodecContext *enc, int size)
  489. {
  490. int frame_size;
  491. if (enc->frame_size <= 1) {
  492. int bits_per_sample = av_get_bits_per_sample(enc->codec_id);
  493. if (bits_per_sample) {
  494. if (enc->channels == 0)
  495. return -1;
  496. frame_size = (size << 3) / (bits_per_sample * enc->channels);
  497. } else {
  498. /* used for example by ADPCM codecs */
  499. if (enc->bit_rate == 0)
  500. return -1;
  501. frame_size = (size * 8 * enc->sample_rate) / enc->bit_rate;
  502. }
  503. } else {
  504. frame_size = enc->frame_size;
  505. }
  506. return frame_size;
  507. }
  508. /**
  509. * Return the frame duration in seconds, return 0 if not available.
  510. */
  511. static void compute_frame_duration(int *pnum, int *pden, AVStream *st,
  512. AVCodecParserContext *pc, AVPacket *pkt)
  513. {
  514. int frame_size;
  515. *pnum = 0;
  516. *pden = 0;
  517. switch(st->codec->codec_type) {
  518. case CODEC_TYPE_VIDEO:
  519. if(st->time_base.num*1000LL > st->time_base.den){
  520. *pnum = st->time_base.num;
  521. *pden = st->time_base.den;
  522. }else if(st->codec->time_base.num*1000LL > st->codec->time_base.den){
  523. *pnum = st->codec->time_base.num;
  524. *pden = st->codec->time_base.den;
  525. if (pc && pc->repeat_pict) {
  526. *pden *= 2;
  527. *pnum = (*pnum) * (2 + pc->repeat_pict);
  528. }
  529. }
  530. break;
  531. case CODEC_TYPE_AUDIO:
  532. frame_size = get_audio_frame_size(st->codec, pkt->size);
  533. if (frame_size < 0)
  534. break;
  535. *pnum = frame_size;
  536. *pden = st->codec->sample_rate;
  537. break;
  538. default:
  539. break;
  540. }
  541. }
  542. static int is_intra_only(AVCodecContext *enc){
  543. if(enc->codec_type == CODEC_TYPE_AUDIO){
  544. return 1;
  545. }else if(enc->codec_type == CODEC_TYPE_VIDEO){
  546. switch(enc->codec_id){
  547. case CODEC_ID_MJPEG:
  548. case CODEC_ID_MJPEGB:
  549. case CODEC_ID_LJPEG:
  550. case CODEC_ID_RAWVIDEO:
  551. case CODEC_ID_DVVIDEO:
  552. case CODEC_ID_HUFFYUV:
  553. case CODEC_ID_FFVHUFF:
  554. case CODEC_ID_ASV1:
  555. case CODEC_ID_ASV2:
  556. case CODEC_ID_VCR1:
  557. return 1;
  558. default: break;
  559. }
  560. }
  561. return 0;
  562. }
  563. static int64_t lsb2full(int64_t lsb, int64_t last_ts, int lsb_bits){
  564. int64_t mask = lsb_bits < 64 ? (1LL<<lsb_bits)-1 : -1LL;
  565. int64_t delta= last_ts - mask/2;
  566. return ((lsb - delta)&mask) + delta;
  567. }
  568. static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
  569. AVCodecParserContext *pc, AVPacket *pkt)
  570. {
  571. int num, den, presentation_delayed;
  572. /* handle wrapping */
  573. if(st->cur_dts != AV_NOPTS_VALUE){
  574. if(pkt->pts != AV_NOPTS_VALUE)
  575. pkt->pts= lsb2full(pkt->pts, st->cur_dts, st->pts_wrap_bits);
  576. if(pkt->dts != AV_NOPTS_VALUE)
  577. pkt->dts= lsb2full(pkt->dts, st->cur_dts, st->pts_wrap_bits);
  578. }
  579. if (pkt->duration == 0) {
  580. compute_frame_duration(&num, &den, st, pc, pkt);
  581. if (den && num) {
  582. pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
  583. }
  584. }
  585. if(is_intra_only(st->codec))
  586. pkt->flags |= PKT_FLAG_KEY;
  587. /* do we have a video B frame ? */
  588. presentation_delayed = 0;
  589. if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
  590. /* XXX: need has_b_frame, but cannot get it if the codec is
  591. not initialized */
  592. if (( st->codec->codec_id == CODEC_ID_H264
  593. || st->codec->has_b_frames) &&
  594. pc && pc->pict_type != FF_B_TYPE)
  595. presentation_delayed = 1;
  596. /* this may be redundant, but it shouldnt hurt */
  597. if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
  598. presentation_delayed = 1;
  599. }
  600. if(st->cur_dts == AV_NOPTS_VALUE){
  601. if(presentation_delayed) st->cur_dts = -pkt->duration;
  602. else st->cur_dts = 0;
  603. }
  604. // av_log(NULL, AV_LOG_DEBUG, "IN delayed:%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64" st:%d pc:%p\n", presentation_delayed, pkt->pts, pkt->dts, st->cur_dts, pkt->stream_index, pc);
  605. /* interpolate PTS and DTS if they are not present */
  606. if (presentation_delayed) {
  607. /* DTS = decompression time stamp */
  608. /* PTS = presentation time stamp */
  609. if (pkt->dts == AV_NOPTS_VALUE) {
  610. /* if we know the last pts, use it */
  611. if(st->last_IP_pts != AV_NOPTS_VALUE)
  612. st->cur_dts = pkt->dts = st->last_IP_pts;
  613. else
  614. pkt->dts = st->cur_dts;
  615. } else {
  616. st->cur_dts = pkt->dts;
  617. }
  618. /* this is tricky: the dts must be incremented by the duration
  619. of the frame we are displaying, i.e. the last I or P frame */
  620. if (st->last_IP_duration == 0)
  621. st->cur_dts += pkt->duration;
  622. else
  623. st->cur_dts += st->last_IP_duration;
  624. st->last_IP_duration = pkt->duration;
  625. st->last_IP_pts= pkt->pts;
  626. /* cannot compute PTS if not present (we can compute it only
  627. by knowing the futur */
  628. } else if(pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE || pkt->duration){
  629. if(pkt->pts != AV_NOPTS_VALUE && pkt->duration){
  630. int64_t old_diff= FFABS(st->cur_dts - pkt->duration - pkt->pts);
  631. int64_t new_diff= FFABS(st->cur_dts - pkt->pts);
  632. if(old_diff < new_diff && old_diff < (pkt->duration>>3)){
  633. pkt->pts += pkt->duration;
  634. // av_log(NULL, AV_LOG_DEBUG, "id:%d old:%"PRId64" new:%"PRId64" dur:%d cur:%"PRId64" size:%d\n", pkt->stream_index, old_diff, new_diff, pkt->duration, st->cur_dts, pkt->size);
  635. }
  636. }
  637. /* presentation is not delayed : PTS and DTS are the same */
  638. if (pkt->pts == AV_NOPTS_VALUE) {
  639. if (pkt->dts == AV_NOPTS_VALUE) {
  640. pkt->pts = st->cur_dts;
  641. pkt->dts = st->cur_dts;
  642. }
  643. else {
  644. st->cur_dts = pkt->dts;
  645. pkt->pts = pkt->dts;
  646. }
  647. } else {
  648. st->cur_dts = pkt->pts;
  649. pkt->dts = pkt->pts;
  650. }
  651. st->cur_dts += pkt->duration;
  652. }
  653. // av_log(NULL, AV_LOG_DEBUG, "OUTdelayed:%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64"\n", presentation_delayed, pkt->pts, pkt->dts, st->cur_dts);
  654. /* update flags */
  655. if (pc) {
  656. pkt->flags = 0;
  657. /* key frame computation */
  658. switch(st->codec->codec_type) {
  659. case CODEC_TYPE_VIDEO:
  660. if (pc->pict_type == FF_I_TYPE)
  661. pkt->flags |= PKT_FLAG_KEY;
  662. break;
  663. case CODEC_TYPE_AUDIO:
  664. pkt->flags |= PKT_FLAG_KEY;
  665. break;
  666. default:
  667. break;
  668. }
  669. }
  670. }
  671. void av_destruct_packet_nofree(AVPacket *pkt)
  672. {
  673. pkt->data = NULL; pkt->size = 0;
  674. }
  675. static int av_read_frame_internal(AVFormatContext *s, AVPacket *pkt)
  676. {
  677. AVStream *st;
  678. int len, ret, i;
  679. for(;;) {
  680. /* select current input stream component */
  681. st = s->cur_st;
  682. if (st) {
  683. if (!st->need_parsing || !st->parser) {
  684. /* no parsing needed: we just output the packet as is */
  685. /* raw data support */
  686. *pkt = s->cur_pkt;
  687. compute_pkt_fields(s, st, NULL, pkt);
  688. s->cur_st = NULL;
  689. break;
  690. } else if (s->cur_len > 0 && st->discard < AVDISCARD_ALL) {
  691. len = av_parser_parse(st->parser, st->codec, &pkt->data, &pkt->size,
  692. s->cur_ptr, s->cur_len,
  693. s->cur_pkt.pts, s->cur_pkt.dts);
  694. s->cur_pkt.pts = AV_NOPTS_VALUE;
  695. s->cur_pkt.dts = AV_NOPTS_VALUE;
  696. /* increment read pointer */
  697. s->cur_ptr += len;
  698. s->cur_len -= len;
  699. /* return packet if any */
  700. if (pkt->size) {
  701. got_packet:
  702. pkt->duration = 0;
  703. pkt->stream_index = st->index;
  704. pkt->pts = st->parser->pts;
  705. pkt->dts = st->parser->dts;
  706. pkt->destruct = av_destruct_packet_nofree;
  707. compute_pkt_fields(s, st, st->parser, pkt);
  708. if((s->iformat->flags & AVFMT_GENERIC_INDEX) && pkt->flags & PKT_FLAG_KEY){
  709. av_add_index_entry(st, st->parser->frame_offset, pkt->dts,
  710. 0, 0, AVINDEX_KEYFRAME);
  711. }
  712. break;
  713. }
  714. } else {
  715. /* free packet */
  716. av_free_packet(&s->cur_pkt);
  717. s->cur_st = NULL;
  718. }
  719. } else {
  720. /* read next packet */
  721. ret = av_read_packet(s, &s->cur_pkt);
  722. if (ret < 0) {
  723. if (ret == AVERROR(EAGAIN))
  724. return ret;
  725. /* return the last frames, if any */
  726. for(i = 0; i < s->nb_streams; i++) {
  727. st = s->streams[i];
  728. if (st->parser && st->need_parsing) {
  729. av_parser_parse(st->parser, st->codec,
  730. &pkt->data, &pkt->size,
  731. NULL, 0,
  732. AV_NOPTS_VALUE, AV_NOPTS_VALUE);
  733. if (pkt->size)
  734. goto got_packet;
  735. }
  736. }
  737. /* no more packets: really terminates parsing */
  738. return ret;
  739. }
  740. st = s->streams[s->cur_pkt.stream_index];
  741. if(st->codec->debug & FF_DEBUG_PTS)
  742. av_log(s, AV_LOG_DEBUG, "av_read_packet stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d\n",
  743. s->cur_pkt.stream_index,
  744. s->cur_pkt.pts,
  745. s->cur_pkt.dts,
  746. s->cur_pkt.size);
  747. s->cur_st = st;
  748. s->cur_ptr = s->cur_pkt.data;
  749. s->cur_len = s->cur_pkt.size;
  750. if (st->need_parsing && !st->parser) {
  751. st->parser = av_parser_init(st->codec->codec_id);
  752. if (!st->parser) {
  753. /* no parser available : just output the raw packets */
  754. st->need_parsing = 0;
  755. }else if(st->need_parsing == 2){
  756. st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
  757. }
  758. if(st->parser && (s->iformat->flags & AVFMT_GENERIC_INDEX)){
  759. st->parser->last_frame_offset=
  760. st->parser->cur_offset= s->cur_pkt.pos;
  761. }
  762. }
  763. }
  764. }
  765. if(st->codec->debug & FF_DEBUG_PTS)
  766. av_log(s, AV_LOG_DEBUG, "av_read_frame_internal stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d\n",
  767. pkt->stream_index,
  768. pkt->pts,
  769. pkt->dts,
  770. pkt->size);
  771. return 0;
  772. }
  773. /**
  774. * Return the next frame of a stream.
  775. *
  776. * The returned packet is valid
  777. * until the next av_read_frame() or until av_close_input_file() and
  778. * must be freed with av_free_packet. For video, the packet contains
  779. * exactly one frame. For audio, it contains an integer number of
  780. * frames if each frame has a known fixed size (e.g. PCM or ADPCM
  781. * data). If the audio frames have a variable size (e.g. MPEG audio),
  782. * then it contains one frame.
  783. *
  784. * pkt->pts, pkt->dts and pkt->duration are always set to correct
  785. * values in AV_TIME_BASE unit (and guessed if the format cannot
  786. * provided them). pkt->pts can be AV_NOPTS_VALUE if the video format
  787. * has B frames, so it is better to rely on pkt->dts if you do not
  788. * decompress the payload.
  789. *
  790. * @return 0 if OK, < 0 if error or end of file.
  791. */
  792. int av_read_frame(AVFormatContext *s, AVPacket *pkt)
  793. {
  794. AVPacketList *pktl;
  795. int eof=0;
  796. const int genpts= s->flags & AVFMT_FLAG_GENPTS;
  797. for(;;){
  798. pktl = s->packet_buffer;
  799. if (pktl) {
  800. AVPacket *next_pkt= &pktl->pkt;
  801. if(genpts && next_pkt->dts != AV_NOPTS_VALUE){
  802. while(pktl && next_pkt->pts == AV_NOPTS_VALUE){
  803. if( pktl->pkt.stream_index == next_pkt->stream_index
  804. && next_pkt->dts < pktl->pkt.dts
  805. && pktl->pkt.pts != pktl->pkt.dts //not b frame
  806. /*&& pktl->pkt.dts != AV_NOPTS_VALUE*/){
  807. next_pkt->pts= pktl->pkt.dts;
  808. }
  809. pktl= pktl->next;
  810. }
  811. pktl = s->packet_buffer;
  812. }
  813. if( next_pkt->pts != AV_NOPTS_VALUE
  814. || next_pkt->dts == AV_NOPTS_VALUE
  815. || !genpts || eof){
  816. /* read packet from packet buffer, if there is data */
  817. *pkt = *next_pkt;
  818. s->packet_buffer = pktl->next;
  819. av_free(pktl);
  820. return 0;
  821. }
  822. }
  823. if(genpts){
  824. AVPacketList **plast_pktl= &s->packet_buffer;
  825. int ret= av_read_frame_internal(s, pkt);
  826. if(ret<0){
  827. if(pktl && ret != AVERROR(EAGAIN)){
  828. eof=1;
  829. continue;
  830. }else
  831. return ret;
  832. }
  833. /* duplicate the packet */
  834. if (av_dup_packet(pkt) < 0)
  835. return AVERROR_NOMEM;
  836. while(*plast_pktl) plast_pktl= &(*plast_pktl)->next; //FIXME maybe maintain pointer to the last?
  837. pktl = av_mallocz(sizeof(AVPacketList));
  838. if (!pktl)
  839. return AVERROR_NOMEM;
  840. /* add the packet in the buffered packet list */
  841. *plast_pktl = pktl;
  842. pktl->pkt= *pkt;
  843. }else{
  844. assert(!s->packet_buffer);
  845. return av_read_frame_internal(s, pkt);
  846. }
  847. }
  848. }
  849. /* XXX: suppress the packet queue */
  850. static void flush_packet_queue(AVFormatContext *s)
  851. {
  852. AVPacketList *pktl;
  853. for(;;) {
  854. pktl = s->packet_buffer;
  855. if (!pktl)
  856. break;
  857. s->packet_buffer = pktl->next;
  858. av_free_packet(&pktl->pkt);
  859. av_free(pktl);
  860. }
  861. }
  862. /*******************************************************/
  863. /* seek support */
  864. int av_find_default_stream_index(AVFormatContext *s)
  865. {
  866. int i;
  867. AVStream *st;
  868. if (s->nb_streams <= 0)
  869. return -1;
  870. for(i = 0; i < s->nb_streams; i++) {
  871. st = s->streams[i];
  872. if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
  873. return i;
  874. }
  875. }
  876. return 0;
  877. }
  878. /**
  879. * Flush the frame reader.
  880. */
  881. static void av_read_frame_flush(AVFormatContext *s)
  882. {
  883. AVStream *st;
  884. int i;
  885. flush_packet_queue(s);
  886. /* free previous packet */
  887. if (s->cur_st) {
  888. if (s->cur_st->parser)
  889. av_free_packet(&s->cur_pkt);
  890. s->cur_st = NULL;
  891. }
  892. /* fail safe */
  893. s->cur_ptr = NULL;
  894. s->cur_len = 0;
  895. /* for each stream, reset read state */
  896. for(i = 0; i < s->nb_streams; i++) {
  897. st = s->streams[i];
  898. if (st->parser) {
  899. av_parser_close(st->parser);
  900. st->parser = NULL;
  901. }
  902. st->last_IP_pts = AV_NOPTS_VALUE;
  903. st->cur_dts = 0; /* we set the current DTS to an unspecified origin */
  904. }
  905. }
  906. /**
  907. * Updates cur_dts of all streams based on given timestamp and AVStream.
  908. *
  909. * Stream ref_st unchanged, others set cur_dts in their native timebase
  910. * only needed for timestamp wrapping or if (dts not set and pts!=dts)
  911. * @param timestamp new dts expressed in time_base of param ref_st
  912. * @param ref_st reference stream giving time_base of param timestamp
  913. */
  914. void av_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp){
  915. int i;
  916. for(i = 0; i < s->nb_streams; i++) {
  917. AVStream *st = s->streams[i];
  918. st->cur_dts = av_rescale(timestamp,
  919. st->time_base.den * (int64_t)ref_st->time_base.num,
  920. st->time_base.num * (int64_t)ref_st->time_base.den);
  921. }
  922. }
  923. /**
  924. * Add a index entry into a sorted list updateing if it is already there.
  925. *
  926. * @param timestamp timestamp in the timebase of the given stream
  927. */
  928. int av_add_index_entry(AVStream *st,
  929. int64_t pos, int64_t timestamp, int size, int distance, int flags)
  930. {
  931. AVIndexEntry *entries, *ie;
  932. int index;
  933. if((unsigned)st->nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
  934. return -1;
  935. entries = av_fast_realloc(st->index_entries,
  936. &st->index_entries_allocated_size,
  937. (st->nb_index_entries + 1) *
  938. sizeof(AVIndexEntry));
  939. if(!entries)
  940. return -1;
  941. st->index_entries= entries;
  942. index= av_index_search_timestamp(st, timestamp, AVSEEK_FLAG_ANY);
  943. if(index<0){
  944. index= st->nb_index_entries++;
  945. ie= &entries[index];
  946. assert(index==0 || ie[-1].timestamp < timestamp);
  947. }else{
  948. ie= &entries[index];
  949. if(ie->timestamp != timestamp){
  950. if(ie->timestamp <= timestamp)
  951. return -1;
  952. memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(st->nb_index_entries - index));
  953. st->nb_index_entries++;
  954. }else if(ie->pos == pos && distance < ie->min_distance) //dont reduce the distance
  955. distance= ie->min_distance;
  956. }
  957. ie->pos = pos;
  958. ie->timestamp = timestamp;
  959. ie->min_distance= distance;
  960. ie->size= size;
  961. ie->flags = flags;
  962. return index;
  963. }
  964. /**
  965. * build an index for raw streams using a parser.
  966. */
  967. static void av_build_index_raw(AVFormatContext *s)
  968. {
  969. AVPacket pkt1, *pkt = &pkt1;
  970. int ret;
  971. AVStream *st;
  972. st = s->streams[0];
  973. av_read_frame_flush(s);
  974. url_fseek(&s->pb, s->data_offset, SEEK_SET);
  975. for(;;) {
  976. ret = av_read_frame(s, pkt);
  977. if (ret < 0)
  978. break;
  979. if (pkt->stream_index == 0 && st->parser &&
  980. (pkt->flags & PKT_FLAG_KEY)) {
  981. av_add_index_entry(st, st->parser->frame_offset, pkt->dts,
  982. 0, 0, AVINDEX_KEYFRAME);
  983. }
  984. av_free_packet(pkt);
  985. }
  986. }
  987. /**
  988. * Returns TRUE if we deal with a raw stream.
  989. *
  990. * Raw codec data and parsing needed.
  991. */
  992. static int is_raw_stream(AVFormatContext *s)
  993. {
  994. AVStream *st;
  995. if (s->nb_streams != 1)
  996. return 0;
  997. st = s->streams[0];
  998. if (!st->need_parsing)
  999. return 0;
  1000. return 1;
  1001. }
  1002. /**
  1003. * Gets the index for a specific timestamp.
  1004. * @param flags if AVSEEK_FLAG_BACKWARD then the returned index will correspond to
  1005. * the timestamp which is <= the requested one, if backward is 0
  1006. * then it will be >=
  1007. * if AVSEEK_FLAG_ANY seek to any frame, only keyframes otherwise
  1008. * @return < 0 if no such timestamp could be found
  1009. */
  1010. int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
  1011. int flags)
  1012. {
  1013. AVIndexEntry *entries= st->index_entries;
  1014. int nb_entries= st->nb_index_entries;
  1015. int a, b, m;
  1016. int64_t timestamp;
  1017. a = - 1;
  1018. b = nb_entries;
  1019. while (b - a > 1) {
  1020. m = (a + b) >> 1;
  1021. timestamp = entries[m].timestamp;
  1022. if(timestamp >= wanted_timestamp)
  1023. b = m;
  1024. if(timestamp <= wanted_timestamp)
  1025. a = m;
  1026. }
  1027. m= (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
  1028. if(!(flags & AVSEEK_FLAG_ANY)){
  1029. while(m>=0 && m<nb_entries && !(entries[m].flags & AVINDEX_KEYFRAME)){
  1030. m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
  1031. }
  1032. }
  1033. if(m == nb_entries)
  1034. return -1;
  1035. return m;
  1036. }
  1037. #define DEBUG_SEEK
  1038. /**
  1039. * Does a binary search using av_index_search_timestamp() and AVCodec.read_timestamp().
  1040. * this isnt supposed to be called directly by a user application, but by demuxers
  1041. * @param target_ts target timestamp in the time base of the given stream
  1042. * @param stream_index stream number
  1043. */
  1044. int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
  1045. AVInputFormat *avif= s->iformat;
  1046. int64_t pos_min, pos_max, pos, pos_limit;
  1047. int64_t ts_min, ts_max, ts;
  1048. int index;
  1049. AVStream *st;
  1050. if (stream_index < 0)
  1051. return -1;
  1052. #ifdef DEBUG_SEEK
  1053. av_log(s, AV_LOG_DEBUG, "read_seek: %d %"PRId64"\n", stream_index, target_ts);
  1054. #endif
  1055. ts_max=
  1056. ts_min= AV_NOPTS_VALUE;
  1057. pos_limit= -1; //gcc falsely says it may be uninitalized
  1058. st= s->streams[stream_index];
  1059. if(st->index_entries){
  1060. AVIndexEntry *e;
  1061. 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()
  1062. index= FFMAX(index, 0);
  1063. e= &st->index_entries[index];
  1064. if(e->timestamp <= target_ts || e->pos == e->min_distance){
  1065. pos_min= e->pos;
  1066. ts_min= e->timestamp;
  1067. #ifdef DEBUG_SEEK
  1068. av_log(s, AV_LOG_DEBUG, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",
  1069. pos_min,ts_min);
  1070. #endif
  1071. }else{
  1072. assert(index==0);
  1073. }
  1074. index= av_index_search_timestamp(st, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
  1075. assert(index < st->nb_index_entries);
  1076. if(index >= 0){
  1077. e= &st->index_entries[index];
  1078. assert(e->timestamp >= target_ts);
  1079. pos_max= e->pos;
  1080. ts_max= e->timestamp;
  1081. pos_limit= pos_max - e->min_distance;
  1082. #ifdef DEBUG_SEEK
  1083. av_log(s, AV_LOG_DEBUG, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64" dts_max=%"PRId64"\n",
  1084. pos_max,pos_limit, ts_max);
  1085. #endif
  1086. }
  1087. }
  1088. pos= av_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit, ts_min, ts_max, flags, &ts, avif->read_timestamp);
  1089. if(pos<0)
  1090. return -1;
  1091. /* do the seek */
  1092. url_fseek(&s->pb, pos, SEEK_SET);
  1093. av_update_cur_dts(s, st, ts);
  1094. return 0;
  1095. }
  1096. /**
  1097. * Does a binary search using read_timestamp().
  1098. * this isnt supposed to be called directly by a user application, but by demuxers
  1099. * @param target_ts target timestamp in the time base of the given stream
  1100. * @param stream_index stream number
  1101. */
  1102. int64_t av_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts, int64_t pos_min, int64_t pos_max, int64_t pos_limit, int64_t ts_min, int64_t ts_max, int flags, int64_t *ts_ret, int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t )){
  1103. int64_t pos, ts;
  1104. int64_t start_pos, filesize;
  1105. int no_change;
  1106. #ifdef DEBUG_SEEK
  1107. av_log(s, AV_LOG_DEBUG, "gen_seek: %d %"PRId64"\n", stream_index, target_ts);
  1108. #endif
  1109. if(ts_min == AV_NOPTS_VALUE){
  1110. pos_min = s->data_offset;
  1111. ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
  1112. if (ts_min == AV_NOPTS_VALUE)
  1113. return -1;
  1114. }
  1115. if(ts_max == AV_NOPTS_VALUE){
  1116. int step= 1024;
  1117. filesize = url_fsize(&s->pb);
  1118. pos_max = filesize - 1;
  1119. do{
  1120. pos_max -= step;
  1121. ts_max = read_timestamp(s, stream_index, &pos_max, pos_max + step);
  1122. step += step;
  1123. }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
  1124. if (ts_max == AV_NOPTS_VALUE)
  1125. return -1;
  1126. for(;;){
  1127. int64_t tmp_pos= pos_max + 1;
  1128. int64_t tmp_ts= read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
  1129. if(tmp_ts == AV_NOPTS_VALUE)
  1130. break;
  1131. ts_max= tmp_ts;
  1132. pos_max= tmp_pos;
  1133. if(tmp_pos >= filesize)
  1134. break;
  1135. }
  1136. pos_limit= pos_max;
  1137. }
  1138. if(ts_min > ts_max){
  1139. return -1;
  1140. }else if(ts_min == ts_max){
  1141. pos_limit= pos_min;
  1142. }
  1143. no_change=0;
  1144. while (pos_min < pos_limit) {
  1145. #ifdef DEBUG_SEEK
  1146. av_log(s, AV_LOG_DEBUG, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64" dts_max=%"PRId64"\n",
  1147. pos_min, pos_max,
  1148. ts_min, ts_max);
  1149. #endif
  1150. assert(pos_limit <= pos_max);
  1151. if(no_change==0){
  1152. int64_t approximate_keyframe_distance= pos_max - pos_limit;
  1153. // interpolate position (better than dichotomy)
  1154. pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)
  1155. + pos_min - approximate_keyframe_distance;
  1156. }else if(no_change==1){
  1157. // bisection, if interpolation failed to change min or max pos last time
  1158. pos = (pos_min + pos_limit)>>1;
  1159. }else{
  1160. // linear search if bisection failed, can only happen if there are very few or no keframes between min/max
  1161. pos=pos_min;
  1162. }
  1163. if(pos <= pos_min)
  1164. pos= pos_min + 1;
  1165. else if(pos > pos_limit)
  1166. pos= pos_limit;
  1167. start_pos= pos;
  1168. ts = read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
  1169. if(pos == pos_max)
  1170. no_change++;
  1171. else
  1172. no_change=0;
  1173. #ifdef DEBUG_SEEK
  1174. av_log(s, AV_LOG_DEBUG, "%"PRId64" %"PRId64" %"PRId64" / %"PRId64" %"PRId64" %"PRId64" target:%"PRId64" limit:%"PRId64" start:%"PRId64" noc:%d\n", pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts, pos_limit, start_pos, no_change);
  1175. #endif
  1176. assert(ts != AV_NOPTS_VALUE);
  1177. if (target_ts <= ts) {
  1178. pos_limit = start_pos - 1;
  1179. pos_max = pos;
  1180. ts_max = ts;
  1181. }
  1182. if (target_ts >= ts) {
  1183. pos_min = pos;
  1184. ts_min = ts;
  1185. }
  1186. }
  1187. pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
  1188. ts = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min : ts_max;
  1189. #ifdef DEBUG_SEEK
  1190. pos_min = pos;
  1191. ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
  1192. pos_min++;
  1193. ts_max = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
  1194. av_log(s, AV_LOG_DEBUG, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n",
  1195. pos, ts_min, target_ts, ts_max);
  1196. #endif
  1197. *ts_ret= ts;
  1198. return pos;
  1199. }
  1200. static int av_seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){
  1201. int64_t pos_min, pos_max;
  1202. #if 0
  1203. AVStream *st;
  1204. if (stream_index < 0)
  1205. return -1;
  1206. st= s->streams[stream_index];
  1207. #endif
  1208. pos_min = s->data_offset;
  1209. pos_max = url_fsize(&s->pb) - 1;
  1210. if (pos < pos_min) pos= pos_min;
  1211. else if(pos > pos_max) pos= pos_max;
  1212. url_fseek(&s->pb, pos, SEEK_SET);
  1213. #if 0
  1214. av_update_cur_dts(s, st, ts);
  1215. #endif
  1216. return 0;
  1217. }
  1218. static int av_seek_frame_generic(AVFormatContext *s,
  1219. int stream_index, int64_t timestamp, int flags)
  1220. {
  1221. int index;
  1222. AVStream *st;
  1223. AVIndexEntry *ie;
  1224. st = s->streams[stream_index];
  1225. index = av_index_search_timestamp(st, timestamp, flags);
  1226. if(index < 0){
  1227. int i;
  1228. AVPacket pkt;
  1229. if(st->index_entries && st->nb_index_entries){
  1230. ie= &st->index_entries[st->nb_index_entries-1];
  1231. url_fseek(&s->pb, ie->pos, SEEK_SET);
  1232. av_update_cur_dts(s, st, ie->timestamp);
  1233. }else
  1234. url_fseek(&s->pb, 0, SEEK_SET);
  1235. for(i=0;; i++) {
  1236. int ret = av_read_frame(s, &pkt);
  1237. if(ret<0)
  1238. break;
  1239. av_free_packet(&pkt);
  1240. if(stream_index == pkt.stream_index){
  1241. if((pkt.flags & PKT_FLAG_KEY) && pkt.dts > timestamp)
  1242. break;
  1243. }
  1244. }
  1245. index = av_index_search_timestamp(st, timestamp, flags);
  1246. }
  1247. if (index < 0)
  1248. return -1;
  1249. av_read_frame_flush(s);
  1250. if (s->iformat->read_seek){
  1251. if(s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
  1252. return 0;
  1253. }
  1254. ie = &st->index_entries[index];
  1255. url_fseek(&s->pb, ie->pos, SEEK_SET);
  1256. av_update_cur_dts(s, st, ie->timestamp);
  1257. return 0;
  1258. }
  1259. /**
  1260. * Seek to the key frame at timestamp.
  1261. * 'timestamp' in 'stream_index'.
  1262. * @param stream_index If stream_index is (-1), a default
  1263. * stream is selected, and timestamp is automatically converted
  1264. * from AV_TIME_BASE units to the stream specific time_base.
  1265. * @param timestamp timestamp in AVStream.time_base units
  1266. * or if there is no stream specified then in AV_TIME_BASE units
  1267. * @param flags flags which select direction and seeking mode
  1268. * @return >= 0 on success
  1269. */
  1270. int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
  1271. {
  1272. int ret;
  1273. AVStream *st;
  1274. av_read_frame_flush(s);
  1275. if(flags & AVSEEK_FLAG_BYTE)
  1276. return av_seek_frame_byte(s, stream_index, timestamp, flags);
  1277. if(stream_index < 0){
  1278. stream_index= av_find_default_stream_index(s);
  1279. if(stream_index < 0)
  1280. return -1;
  1281. st= s->streams[stream_index];
  1282. /* timestamp for default must be expressed in AV_TIME_BASE units */
  1283. timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
  1284. }
  1285. st= s->streams[stream_index];
  1286. /* first, we try the format specific seek */
  1287. if (s->iformat->read_seek)
  1288. ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
  1289. else
  1290. ret = -1;
  1291. if (ret >= 0) {
  1292. return 0;
  1293. }
  1294. if(s->iformat->read_timestamp)
  1295. return av_seek_frame_binary(s, stream_index, timestamp, flags);
  1296. else
  1297. return av_seek_frame_generic(s, stream_index, timestamp, flags);
  1298. }
  1299. /*******************************************************/
  1300. /**
  1301. * Returns TRUE if the stream has accurate timings in any stream.
  1302. *
  1303. * @return TRUE if the stream has accurate timings for at least one component.
  1304. */
  1305. static int av_has_timings(AVFormatContext *ic)
  1306. {
  1307. int i;
  1308. AVStream *st;
  1309. for(i = 0;i < ic->nb_streams; i++) {
  1310. st = ic->streams[i];
  1311. if (st->start_time != AV_NOPTS_VALUE &&
  1312. st->duration != AV_NOPTS_VALUE)
  1313. return 1;
  1314. }
  1315. return 0;
  1316. }
  1317. /**
  1318. * Estimate the stream timings from the one of each components.
  1319. *
  1320. * Also computes the global bitrate if possible.
  1321. */
  1322. static void av_update_stream_timings(AVFormatContext *ic)
  1323. {
  1324. int64_t start_time, start_time1, end_time, end_time1;
  1325. int i;
  1326. AVStream *st;
  1327. start_time = INT64_MAX;
  1328. end_time = INT64_MIN;
  1329. for(i = 0;i < ic->nb_streams; i++) {
  1330. st = ic->streams[i];
  1331. if (st->start_time != AV_NOPTS_VALUE) {
  1332. start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
  1333. if (start_time1 < start_time)
  1334. start_time = start_time1;
  1335. if (st->duration != AV_NOPTS_VALUE) {
  1336. end_time1 = start_time1
  1337. + av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
  1338. if (end_time1 > end_time)
  1339. end_time = end_time1;
  1340. }
  1341. }
  1342. }
  1343. if (start_time != INT64_MAX) {
  1344. ic->start_time = start_time;
  1345. if (end_time != INT64_MIN) {
  1346. ic->duration = end_time - start_time;
  1347. if (ic->file_size > 0) {
  1348. /* compute the bit rate */
  1349. ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE /
  1350. (double)ic->duration;
  1351. }
  1352. }
  1353. }
  1354. }
  1355. static void fill_all_stream_timings(AVFormatContext *ic)
  1356. {
  1357. int i;
  1358. AVStream *st;
  1359. av_update_stream_timings(ic);
  1360. for(i = 0;i < ic->nb_streams; i++) {
  1361. st = ic->streams[i];
  1362. if (st->start_time == AV_NOPTS_VALUE) {
  1363. if(ic->start_time != AV_NOPTS_VALUE)
  1364. st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q, st->time_base);
  1365. if(ic->duration != AV_NOPTS_VALUE)
  1366. st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q, st->time_base);
  1367. }
  1368. }
  1369. }
  1370. static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
  1371. {
  1372. int64_t filesize, duration;
  1373. int bit_rate, i;
  1374. AVStream *st;
  1375. /* if bit_rate is already set, we believe it */
  1376. if (ic->bit_rate == 0) {
  1377. bit_rate = 0;
  1378. for(i=0;i<ic->nb_streams;i++) {
  1379. st = ic->streams[i];
  1380. bit_rate += st->codec->bit_rate;
  1381. }
  1382. ic->bit_rate = bit_rate;
  1383. }
  1384. /* if duration is already set, we believe it */
  1385. if (ic->duration == AV_NOPTS_VALUE &&
  1386. ic->bit_rate != 0 &&
  1387. ic->file_size != 0) {
  1388. filesize = ic->file_size;
  1389. if (filesize > 0) {
  1390. for(i = 0; i < ic->nb_streams; i++) {
  1391. st = ic->streams[i];
  1392. duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);
  1393. if (st->start_time == AV_NOPTS_VALUE ||
  1394. st->duration == AV_NOPTS_VALUE) {
  1395. st->start_time = 0;
  1396. st->duration = duration;
  1397. }
  1398. }
  1399. }
  1400. }
  1401. }
  1402. #define DURATION_MAX_READ_SIZE 250000
  1403. /* only usable for MPEG-PS streams */
  1404. static void av_estimate_timings_from_pts(AVFormatContext *ic, offset_t old_offset)
  1405. {
  1406. AVPacket pkt1, *pkt = &pkt1;
  1407. AVStream *st;
  1408. int read_size, i, ret;
  1409. int64_t end_time;
  1410. int64_t filesize, offset, duration;
  1411. /* free previous packet */
  1412. if (ic->cur_st && ic->cur_st->parser)
  1413. av_free_packet(&ic->cur_pkt);
  1414. ic->cur_st = NULL;
  1415. /* flush packet queue */
  1416. flush_packet_queue(ic);
  1417. for(i=0;i<ic->nb_streams;i++) {
  1418. st = ic->streams[i];
  1419. if (st->parser) {
  1420. av_parser_close(st->parser);
  1421. st->parser= NULL;
  1422. }
  1423. }
  1424. /* we read the first packets to get the first PTS (not fully
  1425. accurate, but it is enough now) */
  1426. url_fseek(&ic->pb, 0, SEEK_SET);
  1427. read_size = 0;
  1428. for(;;) {
  1429. if (read_size >= DURATION_MAX_READ_SIZE)
  1430. break;
  1431. /* if all info is available, we can stop */
  1432. for(i = 0;i < ic->nb_streams; i++) {
  1433. st = ic->streams[i];
  1434. if (st->start_time == AV_NOPTS_VALUE)
  1435. break;
  1436. }
  1437. if (i == ic->nb_streams)
  1438. break;
  1439. ret = av_read_packet(ic, pkt);
  1440. if (ret != 0)
  1441. break;
  1442. read_size += pkt->size;
  1443. st = ic->streams[pkt->stream_index];
  1444. if (pkt->pts != AV_NOPTS_VALUE) {
  1445. if (st->start_time == AV_NOPTS_VALUE)
  1446. st->start_time = pkt->pts;
  1447. }
  1448. av_free_packet(pkt);
  1449. }
  1450. /* estimate the end time (duration) */
  1451. /* XXX: may need to support wrapping */
  1452. filesize = ic->file_size;
  1453. offset = filesize - DURATION_MAX_READ_SIZE;
  1454. if (offset < 0)
  1455. offset = 0;
  1456. url_fseek(&ic->pb, offset, SEEK_SET);
  1457. read_size = 0;
  1458. for(;;) {
  1459. if (read_size >= DURATION_MAX_READ_SIZE)
  1460. break;
  1461. /* if all info is available, we can stop */
  1462. for(i = 0;i < ic->nb_streams; i++) {
  1463. st = ic->streams[i];
  1464. if (st->duration == AV_NOPTS_VALUE)
  1465. break;
  1466. }
  1467. if (i == ic->nb_streams)
  1468. break;
  1469. ret = av_read_packet(ic, pkt);
  1470. if (ret != 0)
  1471. break;
  1472. read_size += pkt->size;
  1473. st = ic->streams[pkt->stream_index];
  1474. if (pkt->pts != AV_NOPTS_VALUE) {
  1475. end_time = pkt->pts;
  1476. duration = end_time - st->start_time;
  1477. if (duration > 0) {
  1478. if (st->duration == AV_NOPTS_VALUE ||
  1479. st->duration < duration)
  1480. st->duration = duration;
  1481. }
  1482. }
  1483. av_free_packet(pkt);
  1484. }
  1485. fill_all_stream_timings(ic);
  1486. url_fseek(&ic->pb, old_offset, SEEK_SET);
  1487. }
  1488. static void av_estimate_timings(AVFormatContext *ic, offset_t old_offset)
  1489. {
  1490. int64_t file_size;
  1491. /* get the file size, if possible */
  1492. if (ic->iformat->flags & AVFMT_NOFILE) {
  1493. file_size = 0;
  1494. } else {
  1495. file_size = url_fsize(&ic->pb);
  1496. if (file_size < 0)
  1497. file_size = 0;
  1498. }
  1499. ic->file_size = file_size;
  1500. if ((!strcmp(ic->iformat->name, "mpeg") ||
  1501. !strcmp(ic->iformat->name, "mpegts")) &&
  1502. file_size && !ic->pb.is_streamed) {
  1503. /* get accurate estimate from the PTSes */
  1504. av_estimate_timings_from_pts(ic, old_offset);
  1505. } else if (av_has_timings(ic)) {
  1506. /* at least one components has timings - we use them for all
  1507. the components */
  1508. fill_all_stream_timings(ic);
  1509. } else {
  1510. /* less precise: use bit rate info */
  1511. av_estimate_timings_from_bit_rate(ic);
  1512. }
  1513. av_update_stream_timings(ic);
  1514. #if 0
  1515. {
  1516. int i;
  1517. AVStream *st;
  1518. for(i = 0;i < ic->nb_streams; i++) {
  1519. st = ic->streams[i];
  1520. printf("%d: start_time: %0.3f duration: %0.3f\n",
  1521. i, (double)st->start_time / AV_TIME_BASE,
  1522. (double)st->duration / AV_TIME_BASE);
  1523. }
  1524. printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
  1525. (double)ic->start_time / AV_TIME_BASE,
  1526. (double)ic->duration / AV_TIME_BASE,
  1527. ic->bit_rate / 1000);
  1528. }
  1529. #endif
  1530. }
  1531. static int has_codec_parameters(AVCodecContext *enc)
  1532. {
  1533. int val;
  1534. switch(enc->codec_type) {
  1535. case CODEC_TYPE_AUDIO:
  1536. val = enc->sample_rate;
  1537. break;
  1538. case CODEC_TYPE_VIDEO:
  1539. val = enc->width && enc->pix_fmt != PIX_FMT_NONE;
  1540. break;
  1541. default:
  1542. val = 1;
  1543. break;
  1544. }
  1545. return (val != 0);
  1546. }
  1547. static int try_decode_frame(AVStream *st, const uint8_t *data, int size)
  1548. {
  1549. int16_t *samples;
  1550. AVCodec *codec;
  1551. int got_picture, ret=0;
  1552. AVFrame picture;
  1553. if(!st->codec->codec){
  1554. codec = avcodec_find_decoder(st->codec->codec_id);
  1555. if (!codec)
  1556. return -1;
  1557. ret = avcodec_open(st->codec, codec);
  1558. if (ret < 0)
  1559. return ret;
  1560. }
  1561. if(!has_codec_parameters(st->codec)){
  1562. switch(st->codec->codec_type) {
  1563. case CODEC_TYPE_VIDEO:
  1564. ret = avcodec_decode_video(st->codec, &picture,
  1565. &got_picture, (uint8_t *)data, size);
  1566. break;
  1567. case CODEC_TYPE_AUDIO:
  1568. samples = av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
  1569. if (!samples)
  1570. goto fail;
  1571. ret = avcodec_decode_audio(st->codec, samples,
  1572. &got_picture, (uint8_t *)data, size);
  1573. av_free(samples);
  1574. break;
  1575. default:
  1576. break;
  1577. }
  1578. }
  1579. fail:
  1580. return ret;
  1581. }
  1582. /* absolute maximum size we read until we abort */
  1583. #define MAX_READ_SIZE 5000000
  1584. #define MAX_STD_TIMEBASES (60*12+5)
  1585. static int get_std_framerate(int i){
  1586. if(i<60*12) return i*1001;
  1587. else return ((int[]){24,30,60,12,15})[i-60*12]*1000*12;
  1588. }
  1589. /**
  1590. * Read packets of a media file to get stream information. This
  1591. * is useful for file formats with no headers such as MPEG. This
  1592. * function also computes the real frame rate in case of mpeg2 repeat
  1593. * frame mode.
  1594. * The logical file position is not changed by this function;
  1595. * examined packets may be buffered for later processing.
  1596. *
  1597. * @param ic media file handle
  1598. * @return >=0 if OK. AVERROR_xxx if error.
  1599. * @todo let user decide somehow what information is needed so we dont waste time geting stuff the user doesnt need
  1600. */
  1601. int av_find_stream_info(AVFormatContext *ic)
  1602. {
  1603. int i, count, ret, read_size, j;
  1604. AVStream *st;
  1605. AVPacket pkt1, *pkt;
  1606. AVPacketList *pktl=NULL, **ppktl;
  1607. int64_t last_dts[MAX_STREAMS];
  1608. int duration_count[MAX_STREAMS]={0};
  1609. double duration_error[MAX_STREAMS][MAX_STD_TIMEBASES]={{0}}; //FIXME malloc()?
  1610. offset_t old_offset = url_ftell(&ic->pb);
  1611. for(i=0;i<ic->nb_streams;i++) {
  1612. st = ic->streams[i];
  1613. if(st->codec->codec_type == CODEC_TYPE_VIDEO){
  1614. /* if(!st->time_base.num)
  1615. st->time_base= */
  1616. if(!st->codec->time_base.num)
  1617. st->codec->time_base= st->time_base;
  1618. }
  1619. //only for the split stuff
  1620. if (!st->parser) {
  1621. st->parser = av_parser_init(st->codec->codec_id);
  1622. if(st->need_parsing == 2 && st->parser){
  1623. st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
  1624. }
  1625. }
  1626. }
  1627. for(i=0;i<MAX_STREAMS;i++){
  1628. last_dts[i]= AV_NOPTS_VALUE;
  1629. }
  1630. count = 0;
  1631. read_size = 0;
  1632. ppktl = &ic->packet_buffer;
  1633. for(;;) {
  1634. /* check if one codec still needs to be handled */
  1635. for(i=0;i<ic->nb_streams;i++) {
  1636. st = ic->streams[i];
  1637. if (!has_codec_parameters(st->codec))
  1638. break;
  1639. /* variable fps and no guess at the real fps */
  1640. if( st->codec->time_base.den >= 101LL*st->codec->time_base.num
  1641. && duration_count[i]<20 && st->codec->codec_type == CODEC_TYPE_VIDEO)
  1642. break;
  1643. if(st->parser && st->parser->parser->split && !st->codec->extradata)
  1644. break;
  1645. }
  1646. if (i == ic->nb_streams) {
  1647. /* NOTE: if the format has no header, then we need to read
  1648. some packets to get most of the streams, so we cannot
  1649. stop here */
  1650. if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
  1651. /* if we found the info for all the codecs, we can stop */
  1652. ret = count;
  1653. break;
  1654. }
  1655. }
  1656. /* we did not get all the codec info, but we read too much data */
  1657. if (read_size >= MAX_READ_SIZE) {
  1658. ret = count;
  1659. break;
  1660. }
  1661. /* NOTE: a new stream can be added there if no header in file
  1662. (AVFMTCTX_NOHEADER) */
  1663. ret = av_read_frame_internal(ic, &pkt1);
  1664. if (ret < 0) {
  1665. /* EOF or error */
  1666. ret = -1; /* we could not have all the codec parameters before EOF */
  1667. for(i=0;i<ic->nb_streams;i++) {
  1668. st = ic->streams[i];
  1669. if (!has_codec_parameters(st->codec)){
  1670. char buf[256];
  1671. avcodec_string(buf, sizeof(buf), st->codec, 0);
  1672. av_log(ic, AV_LOG_INFO, "Could not find codec parameters (%s)\n", buf);
  1673. } else {
  1674. ret = 0;
  1675. }
  1676. }
  1677. break;
  1678. }
  1679. pktl = av_mallocz(sizeof(AVPacketList));
  1680. if (!pktl) {
  1681. ret = AVERROR_NOMEM;
  1682. break;
  1683. }
  1684. /* add the packet in the buffered packet list */
  1685. *ppktl = pktl;
  1686. ppktl = &pktl->next;
  1687. pkt = &pktl->pkt;
  1688. *pkt = pkt1;
  1689. /* duplicate the packet */
  1690. if (av_dup_packet(pkt) < 0) {
  1691. ret = AVERROR_NOMEM;
  1692. break;
  1693. }
  1694. read_size += pkt->size;
  1695. st = ic->streams[pkt->stream_index];
  1696. if(st->codec_info_nb_frames>1) //FIXME move codec_info_nb_frames and codec_info_duration from AVStream into this func
  1697. st->codec_info_duration += pkt->duration;
  1698. if (pkt->duration != 0)
  1699. st->codec_info_nb_frames++;
  1700. {
  1701. int index= pkt->stream_index;
  1702. int64_t last= last_dts[index];
  1703. int64_t duration= pkt->dts - last;
  1704. if(pkt->dts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && duration>0){
  1705. double dur= duration * av_q2d(st->time_base);
  1706. // if(st->codec->codec_type == CODEC_TYPE_VIDEO)
  1707. // av_log(NULL, AV_LOG_ERROR, "%f\n", dur);
  1708. if(duration_count[index] < 2)
  1709. memset(duration_error, 0, sizeof(duration_error));
  1710. for(i=1; i<MAX_STD_TIMEBASES; i++){
  1711. int framerate= get_std_framerate(i);
  1712. int ticks= lrintf(dur*framerate/(1001*12));
  1713. double error= dur - ticks*1001*12/(double)framerate;
  1714. duration_error[index][i] += error*error;
  1715. }
  1716. duration_count[index]++;
  1717. if(st->codec_info_nb_frames == 0 && 0)
  1718. st->codec_info_duration += duration;
  1719. }
  1720. if(last == AV_NOPTS_VALUE || duration_count[index]<=1)
  1721. last_dts[pkt->stream_index]= pkt->dts;
  1722. }
  1723. if(st->parser && st->parser->parser->split && !st->codec->extradata){
  1724. int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
  1725. if(i){
  1726. st->codec->extradata_size= i;
  1727. st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  1728. memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);
  1729. memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  1730. }
  1731. }
  1732. /* if still no information, we try to open the codec and to
  1733. decompress the frame. We try to avoid that in most cases as
  1734. it takes longer and uses more memory. For MPEG4, we need to
  1735. decompress for Quicktime. */
  1736. if (!has_codec_parameters(st->codec) /*&&
  1737. (st->codec->codec_id == CODEC_ID_FLV1 ||
  1738. st->codec->codec_id == CODEC_ID_H264 ||
  1739. st->codec->codec_id == CODEC_ID_H263 ||
  1740. st->codec->codec_id == CODEC_ID_H261 ||
  1741. st->codec->codec_id == CODEC_ID_VORBIS ||
  1742. st->codec->codec_id == CODEC_ID_MJPEG ||
  1743. st->codec->codec_id == CODEC_ID_PNG ||
  1744. st->codec->codec_id == CODEC_ID_PAM ||
  1745. st->codec->codec_id == CODEC_ID_PGM ||
  1746. st->codec->codec_id == CODEC_ID_PGMYUV ||
  1747. st->codec->codec_id == CODEC_ID_PBM ||
  1748. st->codec->codec_id == CODEC_ID_PPM ||
  1749. st->codec->codec_id == CODEC_ID_SHORTEN ||
  1750. (st->codec->codec_id == CODEC_ID_MPEG4 && !st->need_parsing))*/)
  1751. try_decode_frame(st, pkt->data, pkt->size);
  1752. if (av_rescale_q(st->codec_info_duration, st->time_base, AV_TIME_BASE_Q) >= ic->max_analyze_duration) {
  1753. break;
  1754. }
  1755. count++;
  1756. }
  1757. // close codecs which where opened in try_decode_frame()
  1758. for(i=0;i<ic->nb_streams;i++) {
  1759. st = ic->streams[i];
  1760. if(st->codec->codec)
  1761. avcodec_close(st->codec);
  1762. }
  1763. for(i=0;i<ic->nb_streams;i++) {
  1764. st = ic->streams[i];
  1765. if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
  1766. if(st->codec->codec_id == CODEC_ID_RAWVIDEO && !st->codec->codec_tag && !st->codec->bits_per_sample)
  1767. st->codec->codec_tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
  1768. if(duration_count[i]
  1769. && (st->codec->time_base.num*101LL <= st->codec->time_base.den || st->codec->codec_id == CODEC_ID_MPEG2VIDEO) /*&&
  1770. //FIXME we should not special case mpeg2, but this needs testing with non mpeg2 ...
  1771. st->time_base.num*duration_sum[i]/duration_count[i]*101LL > st->time_base.den*/){
  1772. double best_error= 2*av_q2d(st->time_base);
  1773. best_error= best_error*best_error*duration_count[i]*1000*12*30;
  1774. for(j=1; j<MAX_STD_TIMEBASES; j++){
  1775. double error= duration_error[i][j] * get_std_framerate(j);
  1776. // if(st->codec->codec_type == CODEC_TYPE_VIDEO)
  1777. // av_log(NULL, AV_LOG_ERROR, "%f %f\n", get_std_framerate(j) / 12.0/1001, error);
  1778. if(error < best_error){
  1779. best_error= error;
  1780. av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, get_std_framerate(j), 12*1001, INT_MAX);
  1781. }
  1782. }
  1783. }
  1784. if (!st->r_frame_rate.num){
  1785. if( st->codec->time_base.den * (int64_t)st->time_base.num
  1786. <= st->codec->time_base.num * (int64_t)st->time_base.den){
  1787. st->r_frame_rate.num = st->codec->time_base.den;
  1788. st->r_frame_rate.den = st->codec->time_base.num;
  1789. }else{
  1790. st->r_frame_rate.num = st->time_base.den;
  1791. st->r_frame_rate.den = st->time_base.num;
  1792. }
  1793. }
  1794. }
  1795. }
  1796. av_estimate_timings(ic, old_offset);
  1797. #if 0
  1798. /* correct DTS for b frame streams with no timestamps */
  1799. for(i=0;i<ic->nb_streams;i++) {
  1800. st = ic->streams[i];
  1801. if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
  1802. if(b-frames){
  1803. ppktl = &ic->packet_buffer;
  1804. while(ppkt1){
  1805. if(ppkt1->stream_index != i)
  1806. continue;
  1807. if(ppkt1->pkt->dts < 0)
  1808. break;
  1809. if(ppkt1->pkt->pts != AV_NOPTS_VALUE)
  1810. break;
  1811. ppkt1->pkt->dts -= delta;
  1812. ppkt1= ppkt1->next;
  1813. }
  1814. if(ppkt1)
  1815. continue;
  1816. st->cur_dts -= delta;
  1817. }
  1818. }
  1819. }
  1820. #endif
  1821. return ret;
  1822. }
  1823. /*******************************************************/
  1824. /**
  1825. * start playing a network based stream (e.g. RTSP stream) at the
  1826. * current position
  1827. */
  1828. int av_read_play(AVFormatContext *s)
  1829. {
  1830. if (!s->iformat->read_play)
  1831. return AVERROR_NOTSUPP;
  1832. return s->iformat->read_play(s);
  1833. }
  1834. /**
  1835. * Pause a network based stream (e.g. RTSP stream).
  1836. *
  1837. * Use av_read_play() to resume it.
  1838. */
  1839. int av_read_pause(AVFormatContext *s)
  1840. {
  1841. if (!s->iformat->read_pause)
  1842. return AVERROR_NOTSUPP;
  1843. return s->iformat->read_pause(s);
  1844. }
  1845. /**
  1846. * Close a media file (but not its codecs).
  1847. *
  1848. * @param s media file handle
  1849. */
  1850. void av_close_input_file(AVFormatContext *s)
  1851. {
  1852. int i, must_open_file;
  1853. AVStream *st;
  1854. /* free previous packet */
  1855. if (s->cur_st && s->cur_st->parser)
  1856. av_free_packet(&s->cur_pkt);
  1857. if (s->iformat->read_close)
  1858. s->iformat->read_close(s);
  1859. for(i=0;i<s->nb_streams;i++) {
  1860. /* free all data in a stream component */
  1861. st = s->streams[i];
  1862. if (st->parser) {
  1863. av_parser_close(st->parser);
  1864. }
  1865. av_free(st->index_entries);
  1866. av_free(st->codec->extradata);
  1867. av_free(st->codec);
  1868. av_free(st);
  1869. }
  1870. flush_packet_queue(s);
  1871. must_open_file = 1;
  1872. if (s->iformat->flags & AVFMT_NOFILE) {
  1873. must_open_file = 0;
  1874. }
  1875. if (must_open_file) {
  1876. url_fclose(&s->pb);
  1877. }
  1878. av_freep(&s->priv_data);
  1879. av_free(s);
  1880. }
  1881. /**
  1882. * Add a new stream to a media file.
  1883. *
  1884. * Can only be called in the read_header() function. If the flag
  1885. * AVFMTCTX_NOHEADER is in the format context, then new streams
  1886. * can be added in read_packet too.
  1887. *
  1888. * @param s media file handle
  1889. * @param id file format dependent stream id
  1890. */
  1891. AVStream *av_new_stream(AVFormatContext *s, int id)
  1892. {
  1893. AVStream *st;
  1894. int i;
  1895. if (s->nb_streams >= MAX_STREAMS)
  1896. return NULL;
  1897. st = av_mallocz(sizeof(AVStream));
  1898. if (!st)
  1899. return NULL;
  1900. st->codec= avcodec_alloc_context();
  1901. if (s->iformat) {
  1902. /* no default bitrate if decoding */
  1903. st->codec->bit_rate = 0;
  1904. }
  1905. st->index = s->nb_streams;
  1906. st->id = id;
  1907. st->start_time = AV_NOPTS_VALUE;
  1908. st->duration = AV_NOPTS_VALUE;
  1909. st->cur_dts = AV_NOPTS_VALUE;
  1910. /* default pts settings is MPEG like */
  1911. av_set_pts_info(st, 33, 1, 90000);
  1912. st->last_IP_pts = AV_NOPTS_VALUE;
  1913. for(i=0; i<MAX_REORDER_DELAY+1; i++)
  1914. st->pts_buffer[i]= AV_NOPTS_VALUE;
  1915. s->streams[s->nb_streams++] = st;
  1916. return st;
  1917. }
  1918. /************************************************************/
  1919. /* output media file */
  1920. int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
  1921. {
  1922. int ret;
  1923. if (s->oformat->priv_data_size > 0) {
  1924. s->priv_data = av_mallocz(s->oformat->priv_data_size);
  1925. if (!s->priv_data)
  1926. return AVERROR_NOMEM;
  1927. } else
  1928. s->priv_data = NULL;
  1929. if (s->oformat->set_parameters) {
  1930. ret = s->oformat->set_parameters(s, ap);
  1931. if (ret < 0)
  1932. return ret;
  1933. }
  1934. return 0;
  1935. }
  1936. /**
  1937. * allocate the stream private data and write the stream header to an
  1938. * output media file
  1939. *
  1940. * @param s media file handle
  1941. * @return 0 if OK. AVERROR_xxx if error.
  1942. */
  1943. int av_write_header(AVFormatContext *s)
  1944. {
  1945. int ret, i;
  1946. AVStream *st;
  1947. // some sanity checks
  1948. for(i=0;i<s->nb_streams;i++) {
  1949. st = s->streams[i];
  1950. switch (st->codec->codec_type) {
  1951. case CODEC_TYPE_AUDIO:
  1952. if(st->codec->sample_rate<=0){
  1953. av_log(s, AV_LOG_ERROR, "sample rate not set\n");
  1954. return -1;
  1955. }
  1956. break;
  1957. case CODEC_TYPE_VIDEO:
  1958. if(st->codec->time_base.num<=0 || st->codec->time_base.den<=0){ //FIXME audio too?
  1959. av_log(s, AV_LOG_ERROR, "time base not set\n");
  1960. return -1;
  1961. }
  1962. if(st->codec->width<=0 || st->codec->height<=0){
  1963. av_log(s, AV_LOG_ERROR, "dimensions not set\n");
  1964. return -1;
  1965. }
  1966. break;
  1967. }
  1968. if(s->oformat->codec_tag){
  1969. if(st->codec->codec_tag){
  1970. //FIXME
  1971. //check that tag + id is in the table
  1972. //if neither is in the table -> ok
  1973. //if tag is in the table with another id -> FAIL
  1974. //if id is in the table with another tag -> FAIL unless strict < ?
  1975. }else
  1976. st->codec->codec_tag= av_codec_get_tag(s->oformat->codec_tag, st->codec->codec_id);
  1977. }
  1978. }
  1979. if (!s->priv_data && s->oformat->priv_data_size > 0) {
  1980. s->priv_data = av_mallocz(s->oformat->priv_data_size);
  1981. if (!s->priv_data)
  1982. return AVERROR_NOMEM;
  1983. }
  1984. if(s->oformat->write_header){
  1985. ret = s->oformat->write_header(s);
  1986. if (ret < 0)
  1987. return ret;
  1988. }
  1989. /* init PTS generation */
  1990. for(i=0;i<s->nb_streams;i++) {
  1991. int64_t den = AV_NOPTS_VALUE;
  1992. st = s->streams[i];
  1993. switch (st->codec->codec_type) {
  1994. case CODEC_TYPE_AUDIO:
  1995. den = (int64_t)st->time_base.num * st->codec->sample_rate;
  1996. break;
  1997. case CODEC_TYPE_VIDEO:
  1998. den = (int64_t)st->time_base.num * st->codec->time_base.den;
  1999. break;
  2000. default:
  2001. break;
  2002. }
  2003. if (den != AV_NOPTS_VALUE) {
  2004. if (den <= 0)
  2005. return AVERROR_INVALIDDATA;
  2006. av_frac_init(&st->pts, 0, 0, den);
  2007. }
  2008. }
  2009. return 0;
  2010. }
  2011. //FIXME merge with compute_pkt_fields
  2012. static int compute_pkt_fields2(AVStream *st, AVPacket *pkt){
  2013. int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);
  2014. int num, den, frame_size, i;
  2015. // av_log(st->codec, AV_LOG_DEBUG, "av_write_frame: pts:%"PRId64" dts:%"PRId64" cur_dts:%"PRId64" b:%d size:%d st:%d\n", pkt->pts, pkt->dts, st->cur_dts, delay, pkt->size, pkt->stream_index);
  2016. /* if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
  2017. return -1;*/
  2018. /* duration field */
  2019. if (pkt->duration == 0) {
  2020. compute_frame_duration(&num, &den, st, NULL, pkt);
  2021. if (den && num) {
  2022. pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
  2023. }
  2024. }
  2025. //XXX/FIXME this is a temporary hack until all encoders output pts
  2026. if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay){
  2027. pkt->dts=
  2028. // pkt->pts= st->cur_dts;
  2029. pkt->pts= st->pts.val;
  2030. }
  2031. //calculate dts from pts
  2032. if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE){
  2033. st->pts_buffer[0]= pkt->pts;
  2034. for(i=1; i<delay+1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
  2035. st->pts_buffer[i]= (i-delay-1) * pkt->duration;
  2036. for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
  2037. FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
  2038. pkt->dts= st->pts_buffer[0];
  2039. }
  2040. if(st->cur_dts && st->cur_dts != AV_NOPTS_VALUE && st->cur_dts >= pkt->dts){
  2041. av_log(NULL, AV_LOG_ERROR, "error, non monotone timestamps %"PRId64" >= %"PRId64"\n", st->cur_dts, pkt->dts);
  2042. return -1;
  2043. }
  2044. if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts){
  2045. av_log(NULL, AV_LOG_ERROR, "error, pts < dts\n");
  2046. return -1;
  2047. }
  2048. // av_log(NULL, AV_LOG_DEBUG, "av_write_frame: pts2:%"PRId64" dts2:%"PRId64"\n", pkt->pts, pkt->dts);
  2049. st->cur_dts= pkt->dts;
  2050. st->pts.val= pkt->dts;
  2051. /* update pts */
  2052. switch (st->codec->codec_type) {
  2053. case CODEC_TYPE_AUDIO:
  2054. frame_size = get_audio_frame_size(st->codec, pkt->size);
  2055. /* HACK/FIXME, we skip the initial 0-size packets as they are most likely equal to the encoder delay,
  2056. but it would be better if we had the real timestamps from the encoder */
  2057. if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) {
  2058. av_frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
  2059. }
  2060. break;
  2061. case CODEC_TYPE_VIDEO:
  2062. av_frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
  2063. break;
  2064. default:
  2065. break;
  2066. }
  2067. return 0;
  2068. }
  2069. static void truncate_ts(AVStream *st, AVPacket *pkt){
  2070. int64_t pts_mask = (2LL << (st->pts_wrap_bits-1)) - 1;
  2071. // if(pkt->dts < 0)
  2072. // pkt->dts= 0; //this happens for low_delay=0 and b frames, FIXME, needs further invstigation about what we should do here
  2073. if (pkt->pts != AV_NOPTS_VALUE)
  2074. pkt->pts &= pts_mask;
  2075. if (pkt->dts != AV_NOPTS_VALUE)
  2076. pkt->dts &= pts_mask;
  2077. }
  2078. /**
  2079. * Write a packet to an output media file.
  2080. *
  2081. * The packet shall contain one audio or video frame.
  2082. * The packet must be correctly interleaved according to the container specification,
  2083. * if not then av_interleaved_write_frame must be used
  2084. *
  2085. * @param s media file handle
  2086. * @param pkt the packet, which contains the stream_index, buf/buf_size, dts/pts, ...
  2087. * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
  2088. */
  2089. int av_write_frame(AVFormatContext *s, AVPacket *pkt)
  2090. {
  2091. int ret;
  2092. ret=compute_pkt_fields2(s->streams[pkt->stream_index], pkt);
  2093. if(ret<0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
  2094. return ret;
  2095. truncate_ts(s->streams[pkt->stream_index], pkt);
  2096. ret= s->oformat->write_packet(s, pkt);
  2097. if(!ret)
  2098. ret= url_ferror(&s->pb);
  2099. return ret;
  2100. }
  2101. /**
  2102. * Interleave a packet per DTS in an output media file.
  2103. *
  2104. * Packets with pkt->destruct == av_destruct_packet will be freed inside this function,
  2105. * so they cannot be used after it, note calling av_free_packet() on them is still safe.
  2106. *
  2107. * @param s media file handle
  2108. * @param out the interleaved packet will be output here
  2109. * @param in the input packet
  2110. * @param flush 1 if no further packets are available as input and all
  2111. * remaining packets should be output
  2112. * @return 1 if a packet was output, 0 if no packet could be output,
  2113. * < 0 if an error occured
  2114. */
  2115. int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush){
  2116. AVPacketList *pktl, **next_point, *this_pktl;
  2117. int stream_count=0;
  2118. int streams[MAX_STREAMS];
  2119. if(pkt){
  2120. AVStream *st= s->streams[ pkt->stream_index];
  2121. // assert(pkt->destruct != av_destruct_packet); //FIXME
  2122. this_pktl = av_mallocz(sizeof(AVPacketList));
  2123. this_pktl->pkt= *pkt;
  2124. if(pkt->destruct == av_destruct_packet)
  2125. pkt->destruct= NULL; // non shared -> must keep original from being freed
  2126. else
  2127. av_dup_packet(&this_pktl->pkt); //shared -> must dup
  2128. next_point = &s->packet_buffer;
  2129. while(*next_point){
  2130. AVStream *st2= s->streams[ (*next_point)->pkt.stream_index];
  2131. int64_t left= st2->time_base.num * (int64_t)st ->time_base.den;
  2132. int64_t right= st ->time_base.num * (int64_t)st2->time_base.den;
  2133. if((*next_point)->pkt.dts * left > pkt->dts * right) //FIXME this can overflow
  2134. break;
  2135. next_point= &(*next_point)->next;
  2136. }
  2137. this_pktl->next= *next_point;
  2138. *next_point= this_pktl;
  2139. }
  2140. memset(streams, 0, sizeof(streams));
  2141. pktl= s->packet_buffer;
  2142. while(pktl){
  2143. //av_log(s, AV_LOG_DEBUG, "show st:%d dts:%"PRId64"\n", pktl->pkt.stream_index, pktl->pkt.dts);
  2144. if(streams[ pktl->pkt.stream_index ] == 0)
  2145. stream_count++;
  2146. streams[ pktl->pkt.stream_index ]++;
  2147. pktl= pktl->next;
  2148. }
  2149. if(s->nb_streams == stream_count || (flush && stream_count)){
  2150. pktl= s->packet_buffer;
  2151. *out= pktl->pkt;
  2152. s->packet_buffer= pktl->next;
  2153. av_freep(&pktl);
  2154. return 1;
  2155. }else{
  2156. av_init_packet(out);
  2157. return 0;
  2158. }
  2159. }
  2160. /**
  2161. * Interleaves a AVPacket correctly so it can be muxed.
  2162. * @param out the interleaved packet will be output here
  2163. * @param in the input packet
  2164. * @param flush 1 if no further packets are available as input and all
  2165. * remaining packets should be output
  2166. * @return 1 if a packet was output, 0 if no packet could be output,
  2167. * < 0 if an error occured
  2168. */
  2169. static int av_interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush){
  2170. if(s->oformat->interleave_packet)
  2171. return s->oformat->interleave_packet(s, out, in, flush);
  2172. else
  2173. return av_interleave_packet_per_dts(s, out, in, flush);
  2174. }
  2175. /**
  2176. * Writes a packet to an output media file ensuring correct interleaving.
  2177. *
  2178. * The packet must contain one audio or video frame.
  2179. * If the packets are already correctly interleaved the application should
  2180. * call av_write_frame() instead as its slightly faster, its also important
  2181. * to keep in mind that completly non interleaved input will need huge amounts
  2182. * of memory to interleave with this, so its prefereable to interleave at the
  2183. * demuxer level
  2184. *
  2185. * @param s media file handle
  2186. * @param pkt the packet, which contains the stream_index, buf/buf_size, dts/pts, ...
  2187. * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
  2188. */
  2189. int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){
  2190. AVStream *st= s->streams[ pkt->stream_index];
  2191. //FIXME/XXX/HACK drop zero sized packets
  2192. if(st->codec->codec_type == CODEC_TYPE_AUDIO && pkt->size==0)
  2193. return 0;
  2194. //av_log(NULL, AV_LOG_DEBUG, "av_interleaved_write_frame %d %"PRId64" %"PRId64"\n", pkt->size, pkt->dts, pkt->pts);
  2195. if(compute_pkt_fields2(st, pkt) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
  2196. return -1;
  2197. if(pkt->dts == AV_NOPTS_VALUE)
  2198. return -1;
  2199. for(;;){
  2200. AVPacket opkt;
  2201. int ret= av_interleave_packet(s, &opkt, pkt, 0);
  2202. if(ret<=0) //FIXME cleanup needed for ret<0 ?
  2203. return ret;
  2204. truncate_ts(s->streams[opkt.stream_index], &opkt);
  2205. ret= s->oformat->write_packet(s, &opkt);
  2206. av_free_packet(&opkt);
  2207. pkt= NULL;
  2208. if(ret<0)
  2209. return ret;
  2210. if(url_ferror(&s->pb))
  2211. return url_ferror(&s->pb);
  2212. }
  2213. }
  2214. /**
  2215. * @brief Write the stream trailer to an output media file and
  2216. * free the file private data.
  2217. *
  2218. * @param s media file handle
  2219. * @return 0 if OK. AVERROR_xxx if error.
  2220. */
  2221. int av_write_trailer(AVFormatContext *s)
  2222. {
  2223. int ret, i;
  2224. for(;;){
  2225. AVPacket pkt;
  2226. ret= av_interleave_packet(s, &pkt, NULL, 1);
  2227. if(ret<0) //FIXME cleanup needed for ret<0 ?
  2228. goto fail;
  2229. if(!ret)
  2230. break;
  2231. truncate_ts(s->streams[pkt.stream_index], &pkt);
  2232. ret= s->oformat->write_packet(s, &pkt);
  2233. av_free_packet(&pkt);
  2234. if(ret<0)
  2235. goto fail;
  2236. if(url_ferror(&s->pb))
  2237. goto fail;
  2238. }
  2239. if(s->oformat->write_trailer)
  2240. ret = s->oformat->write_trailer(s);
  2241. fail:
  2242. if(ret == 0)
  2243. ret=url_ferror(&s->pb);
  2244. for(i=0;i<s->nb_streams;i++)
  2245. av_freep(&s->streams[i]->priv_data);
  2246. av_freep(&s->priv_data);
  2247. return ret;
  2248. }
  2249. /* "user interface" functions */
  2250. void dump_format(AVFormatContext *ic,
  2251. int index,
  2252. const char *url,
  2253. int is_output)
  2254. {
  2255. int i, flags;
  2256. char buf[256];
  2257. av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",
  2258. is_output ? "Output" : "Input",
  2259. index,
  2260. is_output ? ic->oformat->name : ic->iformat->name,
  2261. is_output ? "to" : "from", url);
  2262. if (!is_output) {
  2263. av_log(NULL, AV_LOG_INFO, " Duration: ");
  2264. if (ic->duration != AV_NOPTS_VALUE) {
  2265. int hours, mins, secs, us;
  2266. secs = ic->duration / AV_TIME_BASE;
  2267. us = ic->duration % AV_TIME_BASE;
  2268. mins = secs / 60;
  2269. secs %= 60;
  2270. hours = mins / 60;
  2271. mins %= 60;
  2272. av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%01d", hours, mins, secs,
  2273. (10 * us) / AV_TIME_BASE);
  2274. } else {
  2275. av_log(NULL, AV_LOG_INFO, "N/A");
  2276. }
  2277. if (ic->start_time != AV_NOPTS_VALUE) {
  2278. int secs, us;
  2279. av_log(NULL, AV_LOG_INFO, ", start: ");
  2280. secs = ic->start_time / AV_TIME_BASE;
  2281. us = ic->start_time % AV_TIME_BASE;
  2282. av_log(NULL, AV_LOG_INFO, "%d.%06d",
  2283. secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));
  2284. }
  2285. av_log(NULL, AV_LOG_INFO, ", bitrate: ");
  2286. if (ic->bit_rate) {
  2287. av_log(NULL, AV_LOG_INFO,"%d kb/s", ic->bit_rate / 1000);
  2288. } else {
  2289. av_log(NULL, AV_LOG_INFO, "N/A");
  2290. }
  2291. av_log(NULL, AV_LOG_INFO, "\n");
  2292. }
  2293. for(i=0;i<ic->nb_streams;i++) {
  2294. AVStream *st = ic->streams[i];
  2295. int g= ff_gcd(st->time_base.num, st->time_base.den);
  2296. avcodec_string(buf, sizeof(buf), st->codec, is_output);
  2297. av_log(NULL, AV_LOG_INFO, " Stream #%d.%d", index, i);
  2298. /* the pid is an important information, so we display it */
  2299. /* XXX: add a generic system */
  2300. if (is_output)
  2301. flags = ic->oformat->flags;
  2302. else
  2303. flags = ic->iformat->flags;
  2304. if (flags & AVFMT_SHOW_IDS) {
  2305. av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
  2306. }
  2307. if (strlen(st->language) > 0) {
  2308. av_log(NULL, AV_LOG_INFO, "(%s)", st->language);
  2309. }
  2310. av_log(NULL, AV_LOG_DEBUG, ", %d/%d", st->time_base.num/g, st->time_base.den/g);
  2311. av_log(NULL, AV_LOG_INFO, ": %s", buf);
  2312. if(st->codec->codec_type == CODEC_TYPE_VIDEO){
  2313. if(st->r_frame_rate.den && st->r_frame_rate.num)
  2314. av_log(NULL, AV_LOG_INFO, ", %5.2f fps(r)", av_q2d(st->r_frame_rate));
  2315. /* else if(st->time_base.den && st->time_base.num)
  2316. av_log(NULL, AV_LOG_INFO, ", %5.2f fps(m)", 1/av_q2d(st->time_base));*/
  2317. else
  2318. av_log(NULL, AV_LOG_INFO, ", %5.2f fps(c)", 1/av_q2d(st->codec->time_base));
  2319. }
  2320. av_log(NULL, AV_LOG_INFO, "\n");
  2321. }
  2322. }
  2323. typedef struct {
  2324. const char *abv;
  2325. int width, height;
  2326. int frame_rate, frame_rate_base;
  2327. } AbvEntry;
  2328. static AbvEntry frame_abvs[] = {
  2329. { "ntsc", 720, 480, 30000, 1001 },
  2330. { "pal", 720, 576, 25, 1 },
  2331. { "qntsc", 352, 240, 30000, 1001 }, /* VCD compliant ntsc */
  2332. { "qpal", 352, 288, 25, 1 }, /* VCD compliant pal */
  2333. { "sntsc", 640, 480, 30000, 1001 }, /* square pixel ntsc */
  2334. { "spal", 768, 576, 25, 1 }, /* square pixel pal */
  2335. { "film", 352, 240, 24, 1 },
  2336. { "ntsc-film", 352, 240, 24000, 1001 },
  2337. { "sqcif", 128, 96, 0, 0 },
  2338. { "qcif", 176, 144, 0, 0 },
  2339. { "cif", 352, 288, 0, 0 },
  2340. { "4cif", 704, 576, 0, 0 },
  2341. };
  2342. /**
  2343. * parses width and height out of string str.
  2344. */
  2345. int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
  2346. {
  2347. int i;
  2348. int n = sizeof(frame_abvs) / sizeof(AbvEntry);
  2349. const char *p;
  2350. int frame_width = 0, frame_height = 0;
  2351. for(i=0;i<n;i++) {
  2352. if (!strcmp(frame_abvs[i].abv, str)) {
  2353. frame_width = frame_abvs[i].width;
  2354. frame_height = frame_abvs[i].height;
  2355. break;
  2356. }
  2357. }
  2358. if (i == n) {
  2359. p = str;
  2360. frame_width = strtol(p, (char **)&p, 10);
  2361. if (*p)
  2362. p++;
  2363. frame_height = strtol(p, (char **)&p, 10);
  2364. }
  2365. if (frame_width <= 0 || frame_height <= 0)
  2366. return -1;
  2367. *width_ptr = frame_width;
  2368. *height_ptr = frame_height;
  2369. return 0;
  2370. }
  2371. /**
  2372. * Converts frame rate from string to a fraction.
  2373. *
  2374. * First we try to get an exact integer or fractional frame rate.
  2375. * If this fails we convert the frame rate to a double and return
  2376. * an approximate fraction using the DEFAULT_FRAME_RATE_BASE.
  2377. */
  2378. int parse_frame_rate(int *frame_rate, int *frame_rate_base, const char *arg)
  2379. {
  2380. int i;
  2381. char* cp;
  2382. /* First, we check our abbreviation table */
  2383. for (i = 0; i < sizeof(frame_abvs)/sizeof(*frame_abvs); ++i)
  2384. if (!strcmp(frame_abvs[i].abv, arg)) {
  2385. *frame_rate = frame_abvs[i].frame_rate;
  2386. *frame_rate_base = frame_abvs[i].frame_rate_base;
  2387. return 0;
  2388. }
  2389. /* Then, we try to parse it as fraction */
  2390. cp = strchr(arg, '/');
  2391. if (!cp)
  2392. cp = strchr(arg, ':');
  2393. if (cp) {
  2394. char* cpp;
  2395. *frame_rate = strtol(arg, &cpp, 10);
  2396. if (cpp != arg || cpp == cp)
  2397. *frame_rate_base = strtol(cp+1, &cpp, 10);
  2398. else
  2399. *frame_rate = 0;
  2400. }
  2401. else {
  2402. /* Finally we give up and parse it as double */
  2403. AVRational time_base = av_d2q(strtod(arg, 0), DEFAULT_FRAME_RATE_BASE);
  2404. *frame_rate_base = time_base.den;
  2405. *frame_rate = time_base.num;
  2406. }
  2407. if (!*frame_rate || !*frame_rate_base)
  2408. return -1;
  2409. else
  2410. return 0;
  2411. }
  2412. /**
  2413. * Converts date string to number of seconds since Jan 1st, 1970.
  2414. *
  2415. * @code
  2416. * Syntax:
  2417. * - If not a duration:
  2418. * [{YYYY-MM-DD|YYYYMMDD}]{T| }{HH[:MM[:SS[.m...]]][Z]|HH[MM[SS[.m...]]][Z]}
  2419. * Time is localtime unless Z is suffixed to the end. In this case GMT
  2420. * Return the date in micro seconds since 1970
  2421. *
  2422. * - If a duration:
  2423. * HH[:MM[:SS[.m...]]]
  2424. * S+[.m...]
  2425. * @endcode
  2426. */
  2427. #ifndef CONFIG_WINCE
  2428. int64_t parse_date(const char *datestr, int duration)
  2429. {
  2430. const char *p;
  2431. int64_t t;
  2432. struct tm dt;
  2433. int i;
  2434. static const char *date_fmt[] = {
  2435. "%Y-%m-%d",
  2436. "%Y%m%d",
  2437. };
  2438. static const char *time_fmt[] = {
  2439. "%H:%M:%S",
  2440. "%H%M%S",
  2441. };
  2442. const char *q;
  2443. int is_utc, len;
  2444. char lastch;
  2445. int negative = 0;
  2446. #undef time
  2447. time_t now = time(0);
  2448. len = strlen(datestr);
  2449. if (len > 0)
  2450. lastch = datestr[len - 1];
  2451. else
  2452. lastch = '\0';
  2453. is_utc = (lastch == 'z' || lastch == 'Z');
  2454. memset(&dt, 0, sizeof(dt));
  2455. p = datestr;
  2456. q = NULL;
  2457. if (!duration) {
  2458. for (i = 0; i < sizeof(date_fmt) / sizeof(date_fmt[0]); i++) {
  2459. q = small_strptime(p, date_fmt[i], &dt);
  2460. if (q) {
  2461. break;
  2462. }
  2463. }
  2464. if (!q) {
  2465. if (is_utc) {
  2466. dt = *gmtime(&now);
  2467. } else {
  2468. dt = *localtime(&now);
  2469. }
  2470. dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
  2471. } else {
  2472. p = q;
  2473. }
  2474. if (*p == 'T' || *p == 't' || *p == ' ')
  2475. p++;
  2476. for (i = 0; i < sizeof(time_fmt) / sizeof(time_fmt[0]); i++) {
  2477. q = small_strptime(p, time_fmt[i], &dt);
  2478. if (q) {
  2479. break;
  2480. }
  2481. }
  2482. } else {
  2483. if (p[0] == '-') {
  2484. negative = 1;
  2485. ++p;
  2486. }
  2487. q = small_strptime(p, time_fmt[0], &dt);
  2488. if (!q) {
  2489. dt.tm_sec = strtol(p, (char **)&q, 10);
  2490. dt.tm_min = 0;
  2491. dt.tm_hour = 0;
  2492. }
  2493. }
  2494. /* Now we have all the fields that we can get */
  2495. if (!q) {
  2496. if (duration)
  2497. return 0;
  2498. else
  2499. return now * INT64_C(1000000);
  2500. }
  2501. if (duration) {
  2502. t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
  2503. } else {
  2504. dt.tm_isdst = -1; /* unknown */
  2505. if (is_utc) {
  2506. t = mktimegm(&dt);
  2507. } else {
  2508. t = mktime(&dt);
  2509. }
  2510. }
  2511. t *= 1000000;
  2512. if (*q == '.') {
  2513. int val, n;
  2514. q++;
  2515. for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
  2516. if (!isdigit(*q))
  2517. break;
  2518. val += n * (*q - '0');
  2519. }
  2520. t += val;
  2521. }
  2522. return negative ? -t : t;
  2523. }
  2524. #endif /* CONFIG_WINCE */
  2525. /**
  2526. * Attempts to find a specific tag in a URL.
  2527. *
  2528. * syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done.
  2529. * Return 1 if found.
  2530. */
  2531. int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
  2532. {
  2533. const char *p;
  2534. char tag[128], *q;
  2535. p = info;
  2536. if (*p == '?')
  2537. p++;
  2538. for(;;) {
  2539. q = tag;
  2540. while (*p != '\0' && *p != '=' && *p != '&') {
  2541. if ((q - tag) < sizeof(tag) - 1)
  2542. *q++ = *p;
  2543. p++;
  2544. }
  2545. *q = '\0';
  2546. q = arg;
  2547. if (*p == '=') {
  2548. p++;
  2549. while (*p != '&' && *p != '\0') {
  2550. if ((q - arg) < arg_size - 1) {
  2551. if (*p == '+')
  2552. *q++ = ' ';
  2553. else
  2554. *q++ = *p;
  2555. }
  2556. p++;
  2557. }
  2558. *q = '\0';
  2559. }
  2560. if (!strcmp(tag, tag1))
  2561. return 1;
  2562. if (*p != '&')
  2563. break;
  2564. p++;
  2565. }
  2566. return 0;
  2567. }
  2568. /**
  2569. * Returns in 'buf' the path with '%d' replaced by number.
  2570. * Also handles the '%0nd' format where 'n' is the total number
  2571. * of digits and '%%'.
  2572. *
  2573. * @param buf destination buffer
  2574. * @param buf_size destination buffer size
  2575. * @param path numbered sequence string
  2576. * @number frame number
  2577. * @return 0 if OK, -1 if format error.
  2578. */
  2579. int av_get_frame_filename(char *buf, int buf_size,
  2580. const char *path, int number)
  2581. {
  2582. const char *p;
  2583. char *q, buf1[20], c;
  2584. int nd, len, percentd_found;
  2585. q = buf;
  2586. p = path;
  2587. percentd_found = 0;
  2588. for(;;) {
  2589. c = *p++;
  2590. if (c == '\0')
  2591. break;
  2592. if (c == '%') {
  2593. do {
  2594. nd = 0;
  2595. while (isdigit(*p)) {
  2596. nd = nd * 10 + *p++ - '0';
  2597. }
  2598. c = *p++;
  2599. } while (isdigit(c));
  2600. switch(c) {
  2601. case '%':
  2602. goto addchar;
  2603. case 'd':
  2604. if (percentd_found)
  2605. goto fail;
  2606. percentd_found = 1;
  2607. snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
  2608. len = strlen(buf1);
  2609. if ((q - buf + len) > buf_size - 1)
  2610. goto fail;
  2611. memcpy(q, buf1, len);
  2612. q += len;
  2613. break;
  2614. default:
  2615. goto fail;
  2616. }
  2617. } else {
  2618. addchar:
  2619. if ((q - buf) < buf_size - 1)
  2620. *q++ = c;
  2621. }
  2622. }
  2623. if (!percentd_found)
  2624. goto fail;
  2625. *q = '\0';
  2626. return 0;
  2627. fail:
  2628. *q = '\0';
  2629. return -1;
  2630. }
  2631. /**
  2632. * Print nice hexa dump of a buffer
  2633. * @param f stream for output
  2634. * @param buf buffer
  2635. * @param size buffer size
  2636. */
  2637. void av_hex_dump(FILE *f, uint8_t *buf, int size)
  2638. {
  2639. int len, i, j, c;
  2640. for(i=0;i<size;i+=16) {
  2641. len = size - i;
  2642. if (len > 16)
  2643. len = 16;
  2644. fprintf(f, "%08x ", i);
  2645. for(j=0;j<16;j++) {
  2646. if (j < len)
  2647. fprintf(f, " %02x", buf[i+j]);
  2648. else
  2649. fprintf(f, " ");
  2650. }
  2651. fprintf(f, " ");
  2652. for(j=0;j<len;j++) {
  2653. c = buf[i+j];
  2654. if (c < ' ' || c > '~')
  2655. c = '.';
  2656. fprintf(f, "%c", c);
  2657. }
  2658. fprintf(f, "\n");
  2659. }
  2660. }
  2661. /**
  2662. * Print on 'f' a nice dump of a packet
  2663. * @param f stream for output
  2664. * @param pkt packet to dump
  2665. * @param dump_payload true if the payload must be displayed too
  2666. */
  2667. //FIXME needs to know the time_base
  2668. void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload)
  2669. {
  2670. fprintf(f, "stream #%d:\n", pkt->stream_index);
  2671. fprintf(f, " keyframe=%d\n", ((pkt->flags & PKT_FLAG_KEY) != 0));
  2672. fprintf(f, " duration=%0.3f\n", (double)pkt->duration / AV_TIME_BASE);
  2673. /* DTS is _always_ valid after av_read_frame() */
  2674. fprintf(f, " dts=");
  2675. if (pkt->dts == AV_NOPTS_VALUE)
  2676. fprintf(f, "N/A");
  2677. else
  2678. fprintf(f, "%0.3f", (double)pkt->dts / AV_TIME_BASE);
  2679. /* PTS may be not known if B frames are present */
  2680. fprintf(f, " pts=");
  2681. if (pkt->pts == AV_NOPTS_VALUE)
  2682. fprintf(f, "N/A");
  2683. else
  2684. fprintf(f, "%0.3f", (double)pkt->pts / AV_TIME_BASE);
  2685. fprintf(f, "\n");
  2686. fprintf(f, " size=%d\n", pkt->size);
  2687. if (dump_payload)
  2688. av_hex_dump(f, pkt->data, pkt->size);
  2689. }
  2690. void url_split(char *proto, int proto_size,
  2691. char *authorization, int authorization_size,
  2692. char *hostname, int hostname_size,
  2693. int *port_ptr,
  2694. char *path, int path_size,
  2695. const char *url)
  2696. {
  2697. const char *p;
  2698. char *q;
  2699. int port;
  2700. port = -1;
  2701. p = url;
  2702. q = proto;
  2703. while (*p != ':' && *p != '\0') {
  2704. if ((q - proto) < proto_size - 1)
  2705. *q++ = *p;
  2706. p++;
  2707. }
  2708. if (proto_size > 0)
  2709. *q = '\0';
  2710. if (authorization_size > 0)
  2711. authorization[0] = '\0';
  2712. if (*p == '\0') {
  2713. if (proto_size > 0)
  2714. proto[0] = '\0';
  2715. if (hostname_size > 0)
  2716. hostname[0] = '\0';
  2717. p = url;
  2718. } else {
  2719. char *at,*slash; // PETR: position of '@' character and '/' character
  2720. p++;
  2721. if (*p == '/')
  2722. p++;
  2723. if (*p == '/')
  2724. p++;
  2725. at = strchr(p,'@'); // PETR: get the position of '@'
  2726. slash = strchr(p,'/'); // PETR: get position of '/' - end of hostname
  2727. if (at && slash && at > slash) at = NULL; // PETR: not interested in '@' behind '/'
  2728. q = at ? authorization : hostname; // PETR: if '@' exists starting with auth.
  2729. while ((at || *p != ':') && *p != '/' && *p != '?' && *p != '\0') { // PETR:
  2730. if (*p == '@') { // PETR: passed '@'
  2731. if (authorization_size > 0)
  2732. *q = '\0';
  2733. q = hostname;
  2734. at = NULL;
  2735. } else if (!at) { // PETR: hostname
  2736. if ((q - hostname) < hostname_size - 1)
  2737. *q++ = *p;
  2738. } else {
  2739. if ((q - authorization) < authorization_size - 1)
  2740. *q++ = *p;
  2741. }
  2742. p++;
  2743. }
  2744. if (hostname_size > 0)
  2745. *q = '\0';
  2746. if (*p == ':') {
  2747. p++;
  2748. port = strtoul(p, (char **)&p, 10);
  2749. }
  2750. }
  2751. if (port_ptr)
  2752. *port_ptr = port;
  2753. pstrcpy(path, path_size, p);
  2754. }
  2755. /**
  2756. * Set the pts for a given stream.
  2757. *
  2758. * @param s stream
  2759. * @param pts_wrap_bits number of bits effectively used by the pts
  2760. * (used for wrap control, 33 is the value for MPEG)
  2761. * @param pts_num numerator to convert to seconds (MPEG: 1)
  2762. * @param pts_den denominator to convert to seconds (MPEG: 90000)
  2763. */
  2764. void av_set_pts_info(AVStream *s, int pts_wrap_bits,
  2765. int pts_num, int pts_den)
  2766. {
  2767. s->pts_wrap_bits = pts_wrap_bits;
  2768. s->time_base.num = pts_num;
  2769. s->time_base.den = pts_den;
  2770. }
  2771. /* fraction handling */
  2772. /**
  2773. * f = val + (num / den) + 0.5.
  2774. *
  2775. * 'num' is normalized so that it is such as 0 <= num < den.
  2776. *
  2777. * @param f fractional number
  2778. * @param val integer value
  2779. * @param num must be >= 0
  2780. * @param den must be >= 1
  2781. */
  2782. static void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
  2783. {
  2784. num += (den >> 1);
  2785. if (num >= den) {
  2786. val += num / den;
  2787. num = num % den;
  2788. }
  2789. f->val = val;
  2790. f->num = num;
  2791. f->den = den;
  2792. }
  2793. /**
  2794. * Fractionnal addition to f: f = f + (incr / f->den).
  2795. *
  2796. * @param f fractional number
  2797. * @param incr increment, can be positive or negative
  2798. */
  2799. static void av_frac_add(AVFrac *f, int64_t incr)
  2800. {
  2801. int64_t num, den;
  2802. num = f->num + incr;
  2803. den = f->den;
  2804. if (num < 0) {
  2805. f->val += num / den;
  2806. num = num % den;
  2807. if (num < 0) {
  2808. num += den;
  2809. f->val--;
  2810. }
  2811. } else if (num >= den) {
  2812. f->val += num / den;
  2813. num = num % den;
  2814. }
  2815. f->num = num;
  2816. }