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.

3106 lines
92KB

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