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.

2685 lines
75KB

  1. /*
  2. * Various utilities for ffmpeg system
  3. * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  4. *
  5. * This library is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU Lesser General Public
  7. * License as published by the Free Software Foundation; either
  8. * version 2 of the License, or (at your option) any later version.
  9. *
  10. * This library is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. * Lesser General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Lesser General Public
  16. * License along with this library; if not, write to the Free Software
  17. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  18. */
  19. #include "avformat.h"
  20. #undef NDEBUG
  21. #include <assert.h>
  22. AVInputFormat *first_iformat;
  23. AVOutputFormat *first_oformat;
  24. AVImageFormat *first_image_format;
  25. void av_register_input_format(AVInputFormat *format)
  26. {
  27. AVInputFormat **p;
  28. p = &first_iformat;
  29. while (*p != NULL) p = &(*p)->next;
  30. *p = format;
  31. format->next = NULL;
  32. }
  33. void av_register_output_format(AVOutputFormat *format)
  34. {
  35. AVOutputFormat **p;
  36. p = &first_oformat;
  37. while (*p != NULL) p = &(*p)->next;
  38. *p = format;
  39. format->next = NULL;
  40. }
  41. int match_ext(const char *filename, const char *extensions)
  42. {
  43. const char *ext, *p;
  44. char ext1[32], *q;
  45. if(!filename)
  46. return 0;
  47. ext = strrchr(filename, '.');
  48. if (ext) {
  49. ext++;
  50. p = extensions;
  51. for(;;) {
  52. q = ext1;
  53. while (*p != '\0' && *p != ',')
  54. *q++ = *p++;
  55. *q = '\0';
  56. if (!strcasecmp(ext1, ext))
  57. return 1;
  58. if (*p == '\0')
  59. break;
  60. p++;
  61. }
  62. }
  63. return 0;
  64. }
  65. AVOutputFormat *guess_format(const char *short_name, const char *filename,
  66. const char *mime_type)
  67. {
  68. AVOutputFormat *fmt, *fmt_found;
  69. int score_max, score;
  70. /* specific test for image sequences */
  71. if (!short_name && filename &&
  72. filename_number_test(filename) >= 0 &&
  73. guess_image_format(filename)) {
  74. return guess_format("image", NULL, NULL);
  75. }
  76. /* find the proper file type */
  77. fmt_found = NULL;
  78. score_max = 0;
  79. fmt = first_oformat;
  80. while (fmt != NULL) {
  81. score = 0;
  82. if (fmt->name && short_name && !strcmp(fmt->name, short_name))
  83. score += 100;
  84. if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
  85. score += 10;
  86. if (filename && fmt->extensions &&
  87. match_ext(filename, fmt->extensions)) {
  88. score += 5;
  89. }
  90. if (score > score_max) {
  91. score_max = score;
  92. fmt_found = fmt;
  93. }
  94. fmt = fmt->next;
  95. }
  96. return fmt_found;
  97. }
  98. AVOutputFormat *guess_stream_format(const char *short_name, const char *filename,
  99. const char *mime_type)
  100. {
  101. AVOutputFormat *fmt = guess_format(short_name, filename, mime_type);
  102. if (fmt) {
  103. AVOutputFormat *stream_fmt;
  104. char stream_format_name[64];
  105. snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
  106. stream_fmt = guess_format(stream_format_name, NULL, NULL);
  107. if (stream_fmt)
  108. fmt = stream_fmt;
  109. }
  110. return fmt;
  111. }
  112. AVInputFormat *av_find_input_format(const char *short_name)
  113. {
  114. AVInputFormat *fmt;
  115. for(fmt = first_iformat; fmt != NULL; fmt = fmt->next) {
  116. if (!strcmp(fmt->name, short_name))
  117. return fmt;
  118. }
  119. return NULL;
  120. }
  121. /* memory handling */
  122. /**
  123. * Default packet destructor
  124. */
  125. static void av_destruct_packet(AVPacket *pkt)
  126. {
  127. av_free(pkt->data);
  128. pkt->data = NULL; pkt->size = 0;
  129. }
  130. /**
  131. * Allocate the payload of a packet and intialized its fields to default values.
  132. *
  133. * @param pkt packet
  134. * @param size wanted payload size
  135. * @return 0 if OK. AVERROR_xxx otherwise.
  136. */
  137. int av_new_packet(AVPacket *pkt, int size)
  138. {
  139. void *data = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
  140. if (!data)
  141. return AVERROR_NOMEM;
  142. memset(data + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  143. av_init_packet(pkt);
  144. pkt->data = data;
  145. pkt->size = size;
  146. pkt->destruct = av_destruct_packet;
  147. return 0;
  148. }
  149. /* This is a hack - the packet memory allocation stuff is broken. The
  150. packet is allocated if it was not really allocated */
  151. int av_dup_packet(AVPacket *pkt)
  152. {
  153. if (pkt->destruct != av_destruct_packet) {
  154. uint8_t *data;
  155. /* we duplicate the packet and don't forget to put the padding
  156. again */
  157. data = av_malloc(pkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
  158. if (!data) {
  159. return AVERROR_NOMEM;
  160. }
  161. memcpy(data, pkt->data, pkt->size);
  162. memset(data + pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  163. pkt->data = data;
  164. pkt->destruct = av_destruct_packet;
  165. }
  166. return 0;
  167. }
  168. /* fifo handling */
  169. int fifo_init(FifoBuffer *f, int size)
  170. {
  171. f->buffer = av_malloc(size);
  172. if (!f->buffer)
  173. return -1;
  174. f->end = f->buffer + size;
  175. f->wptr = f->rptr = f->buffer;
  176. return 0;
  177. }
  178. void fifo_free(FifoBuffer *f)
  179. {
  180. av_free(f->buffer);
  181. }
  182. int fifo_size(FifoBuffer *f, uint8_t *rptr)
  183. {
  184. int size;
  185. if (f->wptr >= rptr) {
  186. size = f->wptr - rptr;
  187. } else {
  188. size = (f->end - rptr) + (f->wptr - f->buffer);
  189. }
  190. return size;
  191. }
  192. /* get data from the fifo (return -1 if not enough data) */
  193. int fifo_read(FifoBuffer *f, uint8_t *buf, int buf_size, uint8_t **rptr_ptr)
  194. {
  195. uint8_t *rptr = *rptr_ptr;
  196. int size, len;
  197. if (f->wptr >= rptr) {
  198. size = f->wptr - rptr;
  199. } else {
  200. size = (f->end - rptr) + (f->wptr - f->buffer);
  201. }
  202. if (size < buf_size)
  203. return -1;
  204. while (buf_size > 0) {
  205. len = f->end - rptr;
  206. if (len > buf_size)
  207. len = buf_size;
  208. memcpy(buf, rptr, len);
  209. buf += len;
  210. rptr += len;
  211. if (rptr >= f->end)
  212. rptr = f->buffer;
  213. buf_size -= len;
  214. }
  215. *rptr_ptr = rptr;
  216. return 0;
  217. }
  218. void fifo_write(FifoBuffer *f, uint8_t *buf, int size, uint8_t **wptr_ptr)
  219. {
  220. int len;
  221. uint8_t *wptr;
  222. wptr = *wptr_ptr;
  223. while (size > 0) {
  224. len = f->end - wptr;
  225. if (len > size)
  226. len = size;
  227. memcpy(wptr, buf, len);
  228. wptr += len;
  229. if (wptr >= f->end)
  230. wptr = f->buffer;
  231. buf += len;
  232. size -= len;
  233. }
  234. *wptr_ptr = wptr;
  235. }
  236. int filename_number_test(const char *filename)
  237. {
  238. char buf[1024];
  239. if(!filename)
  240. return -1;
  241. return get_frame_filename(buf, sizeof(buf), filename, 1);
  242. }
  243. /* guess file format */
  244. AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened)
  245. {
  246. AVInputFormat *fmt1, *fmt;
  247. int score, score_max;
  248. fmt = NULL;
  249. score_max = 0;
  250. for(fmt1 = first_iformat; fmt1 != NULL; fmt1 = fmt1->next) {
  251. if (!is_opened && !(fmt1->flags & AVFMT_NOFILE))
  252. continue;
  253. score = 0;
  254. if (fmt1->read_probe) {
  255. score = fmt1->read_probe(pd);
  256. } else if (fmt1->extensions) {
  257. if (match_ext(pd->filename, fmt1->extensions)) {
  258. score = 50;
  259. }
  260. }
  261. if (score > score_max) {
  262. score_max = score;
  263. fmt = fmt1;
  264. }
  265. }
  266. return fmt;
  267. }
  268. /************************************************************/
  269. /* input media file */
  270. /**
  271. * open a media file from an IO stream. 'fmt' must be specified.
  272. */
  273. static const char* format_to_name(void* ptr)
  274. {
  275. AVFormatContext* fc = (AVFormatContext*) ptr;
  276. if(fc->iformat) return fc->iformat->name;
  277. else if(fc->oformat) return fc->oformat->name;
  278. else return "NULL";
  279. }
  280. static const AVClass av_format_context_class = { "AVFormatContext", format_to_name };
  281. AVFormatContext *av_alloc_format_context(void)
  282. {
  283. AVFormatContext *ic;
  284. ic = av_mallocz(sizeof(AVFormatContext));
  285. if (!ic) return ic;
  286. ic->av_class = &av_format_context_class;
  287. return ic;
  288. }
  289. int av_open_input_stream(AVFormatContext **ic_ptr,
  290. ByteIOContext *pb, const char *filename,
  291. AVInputFormat *fmt, AVFormatParameters *ap)
  292. {
  293. int err;
  294. AVFormatContext *ic;
  295. ic = av_alloc_format_context();
  296. if (!ic) {
  297. err = AVERROR_NOMEM;
  298. goto fail;
  299. }
  300. ic->iformat = fmt;
  301. if (pb)
  302. ic->pb = *pb;
  303. ic->duration = AV_NOPTS_VALUE;
  304. ic->start_time = AV_NOPTS_VALUE;
  305. pstrcpy(ic->filename, sizeof(ic->filename), filename);
  306. /* allocate private data */
  307. if (fmt->priv_data_size > 0) {
  308. ic->priv_data = av_mallocz(fmt->priv_data_size);
  309. if (!ic->priv_data) {
  310. err = AVERROR_NOMEM;
  311. goto fail;
  312. }
  313. } else {
  314. ic->priv_data = NULL;
  315. }
  316. err = ic->iformat->read_header(ic, ap);
  317. if (err < 0)
  318. goto fail;
  319. if (pb)
  320. ic->data_offset = url_ftell(&ic->pb);
  321. *ic_ptr = ic;
  322. return 0;
  323. fail:
  324. if (ic) {
  325. av_freep(&ic->priv_data);
  326. }
  327. av_free(ic);
  328. *ic_ptr = NULL;
  329. return err;
  330. }
  331. #define PROBE_BUF_SIZE 2048
  332. /**
  333. * Open a media file as input. The codec are not opened. Only the file
  334. * header (if present) is read.
  335. *
  336. * @param ic_ptr the opened media file handle is put here
  337. * @param filename filename to open.
  338. * @param fmt if non NULL, force the file format to use
  339. * @param buf_size optional buffer size (zero if default is OK)
  340. * @param ap additionnal parameters needed when opening the file (NULL if default)
  341. * @return 0 if OK. AVERROR_xxx otherwise.
  342. */
  343. int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
  344. AVInputFormat *fmt,
  345. int buf_size,
  346. AVFormatParameters *ap)
  347. {
  348. int err, must_open_file, file_opened;
  349. uint8_t buf[PROBE_BUF_SIZE];
  350. AVProbeData probe_data, *pd = &probe_data;
  351. ByteIOContext pb1, *pb = &pb1;
  352. file_opened = 0;
  353. pd->filename = "";
  354. if (filename)
  355. pd->filename = filename;
  356. pd->buf = buf;
  357. pd->buf_size = 0;
  358. if (!fmt) {
  359. /* guess format if no file can be opened */
  360. fmt = av_probe_input_format(pd, 0);
  361. }
  362. /* do not open file if the format does not need it. XXX: specific
  363. hack needed to handle RTSP/TCP */
  364. must_open_file = 1;
  365. if (fmt && (fmt->flags & AVFMT_NOFILE)) {
  366. must_open_file = 0;
  367. }
  368. if (!fmt || must_open_file) {
  369. /* if no file needed do not try to open one */
  370. if (url_fopen(pb, filename, URL_RDONLY) < 0) {
  371. err = AVERROR_IO;
  372. goto fail;
  373. }
  374. file_opened = 1;
  375. if (buf_size > 0) {
  376. url_setbufsize(pb, buf_size);
  377. }
  378. if (!fmt) {
  379. /* read probe data */
  380. pd->buf_size = get_buffer(pb, buf, PROBE_BUF_SIZE);
  381. url_fseek(pb, 0, SEEK_SET);
  382. }
  383. }
  384. /* guess file format */
  385. if (!fmt) {
  386. fmt = av_probe_input_format(pd, 1);
  387. }
  388. /* if still no format found, error */
  389. if (!fmt) {
  390. err = AVERROR_NOFMT;
  391. goto fail;
  392. }
  393. /* XXX: suppress this hack for redirectors */
  394. #ifdef CONFIG_NETWORK
  395. if (fmt == &redir_demux) {
  396. err = redir_open(ic_ptr, pb);
  397. url_fclose(pb);
  398. return err;
  399. }
  400. #endif
  401. /* check filename in case of an image number is expected */
  402. if (fmt->flags & AVFMT_NEEDNUMBER) {
  403. if (filename_number_test(filename) < 0) {
  404. err = AVERROR_NUMEXPECTED;
  405. goto fail;
  406. }
  407. }
  408. err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap);
  409. if (err)
  410. goto fail;
  411. return 0;
  412. fail:
  413. if (file_opened)
  414. url_fclose(pb);
  415. *ic_ptr = NULL;
  416. return err;
  417. }
  418. /*******************************************************/
  419. /**
  420. * Read a transport packet from a media file. This function is
  421. * absolete and should never be used. Use av_read_frame() instead.
  422. *
  423. * @param s media file handle
  424. * @param pkt is filled
  425. * @return 0 if OK. AVERROR_xxx if error.
  426. */
  427. int av_read_packet(AVFormatContext *s, AVPacket *pkt)
  428. {
  429. return s->iformat->read_packet(s, pkt);
  430. }
  431. /**********************************************************/
  432. /* get the number of samples of an audio frame. Return (-1) if error */
  433. static int get_audio_frame_size(AVCodecContext *enc, int size)
  434. {
  435. int frame_size;
  436. if (enc->frame_size <= 1) {
  437. /* specific hack for pcm codecs because no frame size is
  438. provided */
  439. switch(enc->codec_id) {
  440. case CODEC_ID_PCM_S16LE:
  441. case CODEC_ID_PCM_S16BE:
  442. case CODEC_ID_PCM_U16LE:
  443. case CODEC_ID_PCM_U16BE:
  444. if (enc->channels == 0)
  445. return -1;
  446. frame_size = size / (2 * enc->channels);
  447. break;
  448. case CODEC_ID_PCM_S8:
  449. case CODEC_ID_PCM_U8:
  450. case CODEC_ID_PCM_MULAW:
  451. case CODEC_ID_PCM_ALAW:
  452. if (enc->channels == 0)
  453. return -1;
  454. frame_size = size / (enc->channels);
  455. break;
  456. default:
  457. /* used for example by ADPCM codecs */
  458. if (enc->bit_rate == 0)
  459. return -1;
  460. frame_size = (size * 8 * enc->sample_rate) / enc->bit_rate;
  461. break;
  462. }
  463. } else {
  464. frame_size = enc->frame_size;
  465. }
  466. return frame_size;
  467. }
  468. /* return the frame duration in seconds, return 0 if not available */
  469. static void compute_frame_duration(int *pnum, int *pden, AVStream *st,
  470. AVCodecParserContext *pc, AVPacket *pkt)
  471. {
  472. int frame_size;
  473. *pnum = 0;
  474. *pden = 0;
  475. switch(st->codec.codec_type) {
  476. case CODEC_TYPE_VIDEO:
  477. *pnum = st->codec.frame_rate_base;
  478. *pden = st->codec.frame_rate;
  479. if (pc && pc->repeat_pict) {
  480. *pden *= 2;
  481. *pnum = (*pnum) * (2 + pc->repeat_pict);
  482. }
  483. break;
  484. case CODEC_TYPE_AUDIO:
  485. frame_size = get_audio_frame_size(&st->codec, pkt->size);
  486. if (frame_size < 0)
  487. break;
  488. *pnum = frame_size;
  489. *pden = st->codec.sample_rate;
  490. break;
  491. default:
  492. break;
  493. }
  494. }
  495. static int64_t lsb2full(int64_t lsb, int64_t last_ts, int lsb_bits){
  496. int64_t mask = lsb_bits < 64 ? (1LL<<lsb_bits)-1 : -1LL;
  497. int64_t delta= last_ts - mask/2;
  498. return ((lsb - delta)&mask) + delta;
  499. }
  500. static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
  501. AVCodecParserContext *pc, AVPacket *pkt)
  502. {
  503. int num, den, presentation_delayed;
  504. /* handle wrapping */
  505. if(st->cur_dts != AV_NOPTS_VALUE){
  506. if(pkt->pts != AV_NOPTS_VALUE)
  507. pkt->pts= lsb2full(pkt->pts, st->cur_dts, st->pts_wrap_bits);
  508. if(pkt->dts != AV_NOPTS_VALUE)
  509. pkt->dts= lsb2full(pkt->dts, st->cur_dts, st->pts_wrap_bits);
  510. }
  511. if (pkt->duration == 0) {
  512. compute_frame_duration(&num, &den, st, pc, pkt);
  513. if (den && num) {
  514. pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
  515. }
  516. }
  517. /* do we have a video B frame ? */
  518. presentation_delayed = 0;
  519. if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
  520. /* XXX: need has_b_frame, but cannot get it if the codec is
  521. not initialized */
  522. if ((st->codec.codec_id == CODEC_ID_MPEG1VIDEO ||
  523. st->codec.codec_id == CODEC_ID_MPEG2VIDEO ||
  524. st->codec.codec_id == CODEC_ID_MPEG4 ||
  525. st->codec.codec_id == CODEC_ID_H264) &&
  526. pc && pc->pict_type != FF_B_TYPE)
  527. presentation_delayed = 1;
  528. /* this may be redundant, but it shouldnt hurt */
  529. if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
  530. presentation_delayed = 1;
  531. }
  532. if(st->cur_dts == AV_NOPTS_VALUE){
  533. if(presentation_delayed) st->cur_dts = -pkt->duration;
  534. else st->cur_dts = 0;
  535. }
  536. // av_log(NULL, AV_LOG_DEBUG, "IN delayed:%d pts:%lld, dts:%lld cur_dts:%lld st:%d pc:%p\n", presentation_delayed, pkt->pts, pkt->dts, st->cur_dts, pkt->stream_index, pc);
  537. /* interpolate PTS and DTS if they are not present */
  538. if (presentation_delayed) {
  539. /* DTS = decompression time stamp */
  540. /* PTS = presentation time stamp */
  541. if (pkt->dts == AV_NOPTS_VALUE) {
  542. /* if we know the last pts, use it */
  543. if(st->last_IP_pts != AV_NOPTS_VALUE)
  544. st->cur_dts = pkt->dts = st->last_IP_pts;
  545. else
  546. pkt->dts = st->cur_dts;
  547. } else {
  548. st->cur_dts = pkt->dts;
  549. }
  550. /* this is tricky: the dts must be incremented by the duration
  551. of the frame we are displaying, i.e. the last I or P frame */
  552. if (st->last_IP_duration == 0)
  553. st->cur_dts += pkt->duration;
  554. else
  555. st->cur_dts += st->last_IP_duration;
  556. st->last_IP_duration = pkt->duration;
  557. st->last_IP_pts= pkt->pts;
  558. /* cannot compute PTS if not present (we can compute it only
  559. by knowing the futur */
  560. } else {
  561. /* presentation is not delayed : PTS and DTS are the same */
  562. if (pkt->pts == AV_NOPTS_VALUE) {
  563. if (pkt->dts == AV_NOPTS_VALUE) {
  564. pkt->pts = st->cur_dts;
  565. pkt->dts = st->cur_dts;
  566. }
  567. else {
  568. st->cur_dts = pkt->dts;
  569. pkt->pts = pkt->dts;
  570. }
  571. } else {
  572. st->cur_dts = pkt->pts;
  573. pkt->dts = pkt->pts;
  574. }
  575. st->cur_dts += pkt->duration;
  576. }
  577. // av_log(NULL, AV_LOG_DEBUG, "OUTdelayed:%d pts:%lld, dts:%lld cur_dts:%lld\n", presentation_delayed, pkt->pts, pkt->dts, st->cur_dts);
  578. /* update flags */
  579. if (pc) {
  580. pkt->flags = 0;
  581. /* key frame computation */
  582. switch(st->codec.codec_type) {
  583. case CODEC_TYPE_VIDEO:
  584. if (pc->pict_type == FF_I_TYPE)
  585. pkt->flags |= PKT_FLAG_KEY;
  586. break;
  587. case CODEC_TYPE_AUDIO:
  588. pkt->flags |= PKT_FLAG_KEY;
  589. break;
  590. default:
  591. break;
  592. }
  593. }
  594. /* convert the packet time stamp units */
  595. if(pkt->pts != AV_NOPTS_VALUE)
  596. pkt->pts = av_rescale(pkt->pts, AV_TIME_BASE * (int64_t)st->time_base.num, st->time_base.den);
  597. if(pkt->dts != AV_NOPTS_VALUE)
  598. pkt->dts = av_rescale(pkt->dts, AV_TIME_BASE * (int64_t)st->time_base.num, st->time_base.den);
  599. /* duration field */
  600. pkt->duration = av_rescale(pkt->duration, AV_TIME_BASE * (int64_t)st->time_base.num, st->time_base.den);
  601. }
  602. static void av_destruct_packet_nofree(AVPacket *pkt)
  603. {
  604. pkt->data = NULL; pkt->size = 0;
  605. }
  606. static int av_read_frame_internal(AVFormatContext *s, AVPacket *pkt)
  607. {
  608. AVStream *st;
  609. int len, ret, i;
  610. for(;;) {
  611. /* select current input stream component */
  612. st = s->cur_st;
  613. if (st) {
  614. if (!st->parser) {
  615. /* no parsing needed: we just output the packet as is */
  616. /* raw data support */
  617. *pkt = s->cur_pkt;
  618. compute_pkt_fields(s, st, NULL, pkt);
  619. s->cur_st = NULL;
  620. return 0;
  621. } else if (s->cur_len > 0) {
  622. len = av_parser_parse(st->parser, &st->codec, &pkt->data, &pkt->size,
  623. s->cur_ptr, s->cur_len,
  624. s->cur_pkt.pts, s->cur_pkt.dts);
  625. s->cur_pkt.pts = AV_NOPTS_VALUE;
  626. s->cur_pkt.dts = AV_NOPTS_VALUE;
  627. /* increment read pointer */
  628. s->cur_ptr += len;
  629. s->cur_len -= len;
  630. /* return packet if any */
  631. if (pkt->size) {
  632. got_packet:
  633. pkt->duration = 0;
  634. pkt->stream_index = st->index;
  635. pkt->pts = st->parser->pts;
  636. pkt->dts = st->parser->dts;
  637. pkt->destruct = av_destruct_packet_nofree;
  638. compute_pkt_fields(s, st, st->parser, pkt);
  639. return 0;
  640. }
  641. } else {
  642. /* free packet */
  643. av_free_packet(&s->cur_pkt);
  644. s->cur_st = NULL;
  645. }
  646. } else {
  647. /* read next packet */
  648. ret = av_read_packet(s, &s->cur_pkt);
  649. if (ret < 0) {
  650. if (ret == -EAGAIN)
  651. return ret;
  652. /* return the last frames, if any */
  653. for(i = 0; i < s->nb_streams; i++) {
  654. st = s->streams[i];
  655. if (st->parser) {
  656. av_parser_parse(st->parser, &st->codec,
  657. &pkt->data, &pkt->size,
  658. NULL, 0,
  659. AV_NOPTS_VALUE, AV_NOPTS_VALUE);
  660. if (pkt->size)
  661. goto got_packet;
  662. }
  663. }
  664. /* no more packets: really terminates parsing */
  665. return ret;
  666. }
  667. st = s->streams[s->cur_pkt.stream_index];
  668. s->cur_st = st;
  669. s->cur_ptr = s->cur_pkt.data;
  670. s->cur_len = s->cur_pkt.size;
  671. if (st->need_parsing && !st->parser) {
  672. st->parser = av_parser_init(st->codec.codec_id);
  673. if (!st->parser) {
  674. /* no parser available : just output the raw packets */
  675. st->need_parsing = 0;
  676. }
  677. }
  678. }
  679. }
  680. }
  681. /**
  682. * Return the next frame of a stream. The returned packet is valid
  683. * until the next av_read_frame() or until av_close_input_file() and
  684. * must be freed with av_free_packet. For video, the packet contains
  685. * exactly one frame. For audio, it contains an integer number of
  686. * frames if each frame has a known fixed size (e.g. PCM or ADPCM
  687. * data). If the audio frames have a variable size (e.g. MPEG audio),
  688. * then it contains one frame.
  689. *
  690. * pkt->pts, pkt->dts and pkt->duration are always set to correct
  691. * values in AV_TIME_BASE unit (and guessed if the format cannot
  692. * provided them). pkt->pts can be AV_NOPTS_VALUE if the video format
  693. * has B frames, so it is better to rely on pkt->dts if you do not
  694. * decompress the payload.
  695. *
  696. * Return 0 if OK, < 0 if error or end of file.
  697. */
  698. int av_read_frame(AVFormatContext *s, AVPacket *pkt)
  699. {
  700. AVPacketList *pktl;
  701. pktl = s->packet_buffer;
  702. if (pktl) {
  703. /* read packet from packet buffer, if there is data */
  704. *pkt = pktl->pkt;
  705. s->packet_buffer = pktl->next;
  706. av_free(pktl);
  707. return 0;
  708. } else {
  709. return av_read_frame_internal(s, pkt);
  710. }
  711. }
  712. /* XXX: suppress the packet queue */
  713. static void flush_packet_queue(AVFormatContext *s)
  714. {
  715. AVPacketList *pktl;
  716. for(;;) {
  717. pktl = s->packet_buffer;
  718. if (!pktl)
  719. break;
  720. s->packet_buffer = pktl->next;
  721. av_free_packet(&pktl->pkt);
  722. av_free(pktl);
  723. }
  724. }
  725. /*******************************************************/
  726. /* seek support */
  727. int av_find_default_stream_index(AVFormatContext *s)
  728. {
  729. int i;
  730. AVStream *st;
  731. if (s->nb_streams <= 0)
  732. return -1;
  733. for(i = 0; i < s->nb_streams; i++) {
  734. st = s->streams[i];
  735. if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
  736. return i;
  737. }
  738. }
  739. return 0;
  740. }
  741. /* flush the frame reader */
  742. static void av_read_frame_flush(AVFormatContext *s)
  743. {
  744. AVStream *st;
  745. int i;
  746. flush_packet_queue(s);
  747. /* free previous packet */
  748. if (s->cur_st) {
  749. if (s->cur_st->parser)
  750. av_free_packet(&s->cur_pkt);
  751. s->cur_st = NULL;
  752. }
  753. /* fail safe */
  754. s->cur_ptr = NULL;
  755. s->cur_len = 0;
  756. /* for each stream, reset read state */
  757. for(i = 0; i < s->nb_streams; i++) {
  758. st = s->streams[i];
  759. if (st->parser) {
  760. av_parser_close(st->parser);
  761. st->parser = NULL;
  762. }
  763. st->last_IP_pts = AV_NOPTS_VALUE;
  764. st->cur_dts = 0; /* we set the current DTS to an unspecified origin */
  765. }
  766. }
  767. /**
  768. * add a index entry into a sorted list updateing if it is already there.
  769. * @param timestamp timestamp in the timebase of the given stream
  770. */
  771. int av_add_index_entry(AVStream *st,
  772. int64_t pos, int64_t timestamp, int distance, int flags)
  773. {
  774. AVIndexEntry *entries, *ie;
  775. int index;
  776. entries = av_fast_realloc(st->index_entries,
  777. &st->index_entries_allocated_size,
  778. (st->nb_index_entries + 1) *
  779. sizeof(AVIndexEntry));
  780. st->index_entries= entries;
  781. if(st->nb_index_entries){
  782. index= av_index_search_timestamp(st, timestamp);
  783. ie= &entries[index];
  784. if(ie->timestamp != timestamp){
  785. if(ie->timestamp < timestamp){
  786. index++; //index points to next instead of previous entry, maybe nonexistant
  787. ie= &st->index_entries[index];
  788. }else
  789. assert(index==0);
  790. if(index != st->nb_index_entries){
  791. assert(index < st->nb_index_entries);
  792. memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(st->nb_index_entries - index));
  793. }
  794. st->nb_index_entries++;
  795. }else{
  796. if(ie->pos == pos && distance < ie->min_distance) //dont reduce the distance
  797. distance= ie->min_distance;
  798. }
  799. }else{
  800. index= st->nb_index_entries++;
  801. ie= &entries[index];
  802. }
  803. ie->pos = pos;
  804. ie->timestamp = timestamp;
  805. ie->min_distance= distance;
  806. ie->flags = flags;
  807. return index;
  808. }
  809. /* build an index for raw streams using a parser */
  810. static void av_build_index_raw(AVFormatContext *s)
  811. {
  812. AVPacket pkt1, *pkt = &pkt1;
  813. int ret;
  814. AVStream *st;
  815. st = s->streams[0];
  816. av_read_frame_flush(s);
  817. url_fseek(&s->pb, s->data_offset, SEEK_SET);
  818. for(;;) {
  819. ret = av_read_frame(s, pkt);
  820. if (ret < 0)
  821. break;
  822. if (pkt->stream_index == 0 && st->parser &&
  823. (pkt->flags & PKT_FLAG_KEY)) {
  824. int64_t dts= av_rescale(pkt->dts, st->time_base.den, AV_TIME_BASE*(int64_t)st->time_base.num);
  825. av_add_index_entry(st, st->parser->frame_offset, dts,
  826. 0, AVINDEX_KEYFRAME);
  827. }
  828. av_free_packet(pkt);
  829. }
  830. }
  831. /* return TRUE if we deal with a raw stream (raw codec data and
  832. parsing needed) */
  833. static int is_raw_stream(AVFormatContext *s)
  834. {
  835. AVStream *st;
  836. if (s->nb_streams != 1)
  837. return 0;
  838. st = s->streams[0];
  839. if (!st->need_parsing)
  840. return 0;
  841. return 1;
  842. }
  843. /* return the largest index entry whose timestamp is <=
  844. wanted_timestamp */
  845. int av_index_search_timestamp(AVStream *st, int wanted_timestamp)
  846. {
  847. AVIndexEntry *entries= st->index_entries;
  848. int nb_entries= st->nb_index_entries;
  849. int a, b, m;
  850. int64_t timestamp;
  851. if (nb_entries <= 0)
  852. return -1;
  853. a = 0;
  854. b = nb_entries - 1;
  855. while (a < b) {
  856. m = (a + b + 1) >> 1;
  857. timestamp = entries[m].timestamp;
  858. if (timestamp > wanted_timestamp) {
  859. b = m - 1;
  860. } else {
  861. a = m;
  862. }
  863. }
  864. return a;
  865. }
  866. #define DEBUG_SEEK
  867. /**
  868. * Does a binary search using av_index_search_timestamp() and AVCodec.read_timestamp().
  869. * this isnt supposed to be called directly by a user application, but by demuxers
  870. * @param target_ts target timestamp in the time base of the given stream
  871. * @param stream_index stream number
  872. */
  873. int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts){
  874. AVInputFormat *avif= s->iformat;
  875. int64_t pos_min, pos_max, pos, pos_limit;
  876. int64_t ts_min, ts_max, ts;
  877. int64_t start_pos;
  878. int index, no_change, i;
  879. AVStream *st;
  880. if (stream_index < 0)
  881. return -1;
  882. #ifdef DEBUG_SEEK
  883. av_log(s, AV_LOG_DEBUG, "read_seek: %d %lld\n", stream_index, target_ts);
  884. #endif
  885. ts_max=
  886. ts_min= AV_NOPTS_VALUE;
  887. pos_limit= -1; //gcc falsely says it may be uninitalized
  888. st= s->streams[stream_index];
  889. if(st->index_entries){
  890. AVIndexEntry *e;
  891. index= av_index_search_timestamp(st, target_ts);
  892. e= &st->index_entries[index];
  893. if(e->timestamp <= target_ts || e->pos == e->min_distance){
  894. pos_min= e->pos;
  895. ts_min= e->timestamp;
  896. #ifdef DEBUG_SEEK
  897. av_log(s, AV_LOG_DEBUG, "unsing cached pos_min=0x%llx dts_min=%lld\n",
  898. pos_min,ts_min);
  899. #endif
  900. }else{
  901. assert(index==0);
  902. }
  903. index++;
  904. if(index < st->nb_index_entries){
  905. e= &st->index_entries[index];
  906. assert(e->timestamp >= target_ts);
  907. pos_max= e->pos;
  908. ts_max= e->timestamp;
  909. pos_limit= pos_max - e->min_distance;
  910. #ifdef DEBUG_SEEK
  911. av_log(s, AV_LOG_DEBUG, "unsing cached pos_max=0x%llx pos_limit=0x%llx dts_max=%lld\n",
  912. pos_max,pos_limit, ts_max);
  913. #endif
  914. }
  915. }
  916. if(ts_min == AV_NOPTS_VALUE){
  917. pos_min = s->data_offset;
  918. ts_min = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
  919. if (ts_min == AV_NOPTS_VALUE)
  920. return -1;
  921. }
  922. if(ts_max == AV_NOPTS_VALUE){
  923. int step= 1024;
  924. pos_max = url_filesize(url_fileno(&s->pb)) - 1;
  925. do{
  926. pos_max -= step;
  927. ts_max = avif->read_timestamp(s, stream_index, &pos_max, pos_max + step);
  928. step += step;
  929. }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
  930. if (ts_max == AV_NOPTS_VALUE)
  931. return -1;
  932. for(;;){
  933. int64_t tmp_pos= pos_max + 1;
  934. int64_t tmp_ts= avif->read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
  935. if(tmp_ts == AV_NOPTS_VALUE)
  936. break;
  937. ts_max= tmp_ts;
  938. pos_max= tmp_pos;
  939. }
  940. pos_limit= pos_max;
  941. }
  942. no_change=0;
  943. while (pos_min < pos_limit) {
  944. #ifdef DEBUG_SEEK
  945. av_log(s, AV_LOG_DEBUG, "pos_min=0x%llx pos_max=0x%llx dts_min=%lld dts_max=%lld\n",
  946. pos_min, pos_max,
  947. ts_min, ts_max);
  948. #endif
  949. assert(pos_limit <= pos_max);
  950. if(no_change==0){
  951. int64_t approximate_keyframe_distance= pos_max - pos_limit;
  952. // interpolate position (better than dichotomy)
  953. pos = (int64_t)((double)(pos_max - pos_min) *
  954. (double)(target_ts - ts_min) /
  955. (double)(ts_max - ts_min)) + pos_min - approximate_keyframe_distance;
  956. }else if(no_change==1){
  957. // bisection, if interpolation failed to change min or max pos last time
  958. pos = (pos_min + pos_limit)>>1;
  959. }else{
  960. // linear search if bisection failed, can only happen if there are very few or no keframes between min/max
  961. pos=pos_min;
  962. }
  963. if(pos <= pos_min)
  964. pos= pos_min + 1;
  965. else if(pos > pos_limit)
  966. pos= pos_limit;
  967. start_pos= pos;
  968. ts = avif->read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
  969. if(pos == pos_max)
  970. no_change++;
  971. else
  972. no_change=0;
  973. #ifdef DEBUG_SEEK
  974. av_log(s, AV_LOG_DEBUG, "%Ld %Ld %Ld / %Ld %Ld %Ld target:%Ld limit:%Ld start:%Ld noc:%d\n", pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts, pos_limit, start_pos, no_change);
  975. #endif
  976. assert(ts != AV_NOPTS_VALUE);
  977. if (target_ts < ts) {
  978. pos_limit = start_pos - 1;
  979. pos_max = pos;
  980. ts_max = ts;
  981. } else {
  982. pos_min = pos;
  983. ts_min = ts;
  984. /* check if we are lucky */
  985. if (target_ts == ts)
  986. break;
  987. }
  988. }
  989. pos = pos_min;
  990. #ifdef DEBUG_SEEK
  991. pos_min = pos;
  992. ts_min = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
  993. pos_min++;
  994. ts_max = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
  995. av_log(s, AV_LOG_DEBUG, "pos=0x%llx %lld<=%lld<=%lld\n",
  996. pos, ts_min, target_ts, ts_max);
  997. #endif
  998. /* do the seek */
  999. url_fseek(&s->pb, pos, SEEK_SET);
  1000. ts= av_rescale(ts_min, AV_TIME_BASE*(int64_t)st->time_base.num, st->time_base.den);
  1001. for(i = 0; i < s->nb_streams; i++) {
  1002. st = s->streams[i];
  1003. st->cur_dts = av_rescale(ts, st->time_base.den, AV_TIME_BASE*(int64_t)st->time_base.num);
  1004. }
  1005. return 0;
  1006. }
  1007. static int av_seek_frame_generic(AVFormatContext *s,
  1008. int stream_index, int64_t timestamp)
  1009. {
  1010. int index, i;
  1011. AVStream *st;
  1012. AVIndexEntry *ie;
  1013. if (!s->index_built) {
  1014. if (is_raw_stream(s)) {
  1015. av_build_index_raw(s);
  1016. } else {
  1017. return -1;
  1018. }
  1019. s->index_built = 1;
  1020. }
  1021. st = s->streams[stream_index];
  1022. index = av_index_search_timestamp(st, timestamp);
  1023. if (index < 0)
  1024. return -1;
  1025. /* now we have found the index, we can seek */
  1026. ie = &st->index_entries[index];
  1027. av_read_frame_flush(s);
  1028. url_fseek(&s->pb, ie->pos, SEEK_SET);
  1029. timestamp= av_rescale(ie->timestamp, AV_TIME_BASE*(int64_t)st->time_base.num, st->time_base.den);
  1030. for(i = 0; i < s->nb_streams; i++) {
  1031. st = s->streams[i];
  1032. st->cur_dts = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE*(int64_t)st->time_base.num);
  1033. }
  1034. return 0;
  1035. }
  1036. /**
  1037. * Seek to the key frame just before the frame at timestamp
  1038. * 'timestamp' in 'stream_index'.
  1039. * @param stream_index If stream_index is (-1), a default
  1040. * stream is selected
  1041. * @param timestamp timestamp in AV_TIME_BASE units
  1042. * @return >= 0 on success
  1043. */
  1044. int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp)
  1045. {
  1046. int ret;
  1047. AVStream *st;
  1048. av_read_frame_flush(s);
  1049. if(stream_index < 0){
  1050. stream_index= av_find_default_stream_index(s);
  1051. if(stream_index < 0)
  1052. return -1;
  1053. }
  1054. st= s->streams[stream_index];
  1055. timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
  1056. /* first, we try the format specific seek */
  1057. if (s->iformat->read_seek)
  1058. ret = s->iformat->read_seek(s, stream_index, timestamp);
  1059. else
  1060. ret = -1;
  1061. if (ret >= 0) {
  1062. return 0;
  1063. }
  1064. if(s->iformat->read_timestamp)
  1065. return av_seek_frame_binary(s, stream_index, timestamp);
  1066. else
  1067. return av_seek_frame_generic(s, stream_index, timestamp);
  1068. }
  1069. /*******************************************************/
  1070. /* return TRUE if the stream has accurate timings for at least one component */
  1071. static int av_has_timings(AVFormatContext *ic)
  1072. {
  1073. int i;
  1074. AVStream *st;
  1075. for(i = 0;i < ic->nb_streams; i++) {
  1076. st = ic->streams[i];
  1077. if (st->start_time != AV_NOPTS_VALUE &&
  1078. st->duration != AV_NOPTS_VALUE)
  1079. return 1;
  1080. }
  1081. return 0;
  1082. }
  1083. /* estimate the stream timings from the one of each components. Also
  1084. compute the global bitrate if possible */
  1085. static void av_update_stream_timings(AVFormatContext *ic)
  1086. {
  1087. int64_t start_time, end_time, end_time1;
  1088. int i;
  1089. AVStream *st;
  1090. start_time = MAXINT64;
  1091. end_time = MININT64;
  1092. for(i = 0;i < ic->nb_streams; i++) {
  1093. st = ic->streams[i];
  1094. if (st->start_time != AV_NOPTS_VALUE) {
  1095. if (st->start_time < start_time)
  1096. start_time = st->start_time;
  1097. if (st->duration != AV_NOPTS_VALUE) {
  1098. end_time1 = st->start_time + st->duration;
  1099. if (end_time1 > end_time)
  1100. end_time = end_time1;
  1101. }
  1102. }
  1103. }
  1104. if (start_time != MAXINT64) {
  1105. ic->start_time = start_time;
  1106. if (end_time != MAXINT64) {
  1107. ic->duration = end_time - start_time;
  1108. if (ic->file_size > 0) {
  1109. /* compute the bit rate */
  1110. ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE /
  1111. (double)ic->duration;
  1112. }
  1113. }
  1114. }
  1115. }
  1116. static void fill_all_stream_timings(AVFormatContext *ic)
  1117. {
  1118. int i;
  1119. AVStream *st;
  1120. av_update_stream_timings(ic);
  1121. for(i = 0;i < ic->nb_streams; i++) {
  1122. st = ic->streams[i];
  1123. if (st->start_time == AV_NOPTS_VALUE) {
  1124. st->start_time = ic->start_time;
  1125. st->duration = ic->duration;
  1126. }
  1127. }
  1128. }
  1129. static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
  1130. {
  1131. int64_t filesize, duration;
  1132. int bit_rate, i;
  1133. AVStream *st;
  1134. /* if bit_rate is already set, we believe it */
  1135. if (ic->bit_rate == 0) {
  1136. bit_rate = 0;
  1137. for(i=0;i<ic->nb_streams;i++) {
  1138. st = ic->streams[i];
  1139. bit_rate += st->codec.bit_rate;
  1140. }
  1141. ic->bit_rate = bit_rate;
  1142. }
  1143. /* if duration is already set, we believe it */
  1144. if (ic->duration == AV_NOPTS_VALUE &&
  1145. ic->bit_rate != 0 &&
  1146. ic->file_size != 0) {
  1147. filesize = ic->file_size;
  1148. if (filesize > 0) {
  1149. duration = (int64_t)((8 * AV_TIME_BASE * (double)filesize) / (double)ic->bit_rate);
  1150. for(i = 0; i < ic->nb_streams; i++) {
  1151. st = ic->streams[i];
  1152. if (st->start_time == AV_NOPTS_VALUE ||
  1153. st->duration == AV_NOPTS_VALUE) {
  1154. st->start_time = 0;
  1155. st->duration = duration;
  1156. }
  1157. }
  1158. }
  1159. }
  1160. }
  1161. #define DURATION_MAX_READ_SIZE 250000
  1162. /* only usable for MPEG-PS streams */
  1163. static void av_estimate_timings_from_pts(AVFormatContext *ic)
  1164. {
  1165. AVPacket pkt1, *pkt = &pkt1;
  1166. AVStream *st;
  1167. int read_size, i, ret;
  1168. int64_t start_time, end_time, end_time1;
  1169. int64_t filesize, offset, duration;
  1170. /* free previous packet */
  1171. if (ic->cur_st && ic->cur_st->parser)
  1172. av_free_packet(&ic->cur_pkt);
  1173. ic->cur_st = NULL;
  1174. /* flush packet queue */
  1175. flush_packet_queue(ic);
  1176. /* we read the first packets to get the first PTS (not fully
  1177. accurate, but it is enough now) */
  1178. url_fseek(&ic->pb, 0, SEEK_SET);
  1179. read_size = 0;
  1180. for(;;) {
  1181. if (read_size >= DURATION_MAX_READ_SIZE)
  1182. break;
  1183. /* if all info is available, we can stop */
  1184. for(i = 0;i < ic->nb_streams; i++) {
  1185. st = ic->streams[i];
  1186. if (st->start_time == AV_NOPTS_VALUE)
  1187. break;
  1188. }
  1189. if (i == ic->nb_streams)
  1190. break;
  1191. ret = av_read_packet(ic, pkt);
  1192. if (ret != 0)
  1193. break;
  1194. read_size += pkt->size;
  1195. st = ic->streams[pkt->stream_index];
  1196. if (pkt->pts != AV_NOPTS_VALUE) {
  1197. if (st->start_time == AV_NOPTS_VALUE)
  1198. st->start_time = av_rescale(pkt->pts, st->time_base.num * (int64_t)AV_TIME_BASE, st->time_base.den);
  1199. }
  1200. av_free_packet(pkt);
  1201. }
  1202. /* we compute the minimum start_time and use it as default */
  1203. start_time = MAXINT64;
  1204. for(i = 0; i < ic->nb_streams; i++) {
  1205. st = ic->streams[i];
  1206. if (st->start_time != AV_NOPTS_VALUE &&
  1207. st->start_time < start_time)
  1208. start_time = st->start_time;
  1209. }
  1210. if (start_time != MAXINT64)
  1211. ic->start_time = start_time;
  1212. /* estimate the end time (duration) */
  1213. /* XXX: may need to support wrapping */
  1214. filesize = ic->file_size;
  1215. offset = filesize - DURATION_MAX_READ_SIZE;
  1216. if (offset < 0)
  1217. offset = 0;
  1218. url_fseek(&ic->pb, offset, SEEK_SET);
  1219. read_size = 0;
  1220. for(;;) {
  1221. if (read_size >= DURATION_MAX_READ_SIZE)
  1222. break;
  1223. /* if all info is available, we can stop */
  1224. for(i = 0;i < ic->nb_streams; i++) {
  1225. st = ic->streams[i];
  1226. if (st->duration == AV_NOPTS_VALUE)
  1227. break;
  1228. }
  1229. if (i == ic->nb_streams)
  1230. break;
  1231. ret = av_read_packet(ic, pkt);
  1232. if (ret != 0)
  1233. break;
  1234. read_size += pkt->size;
  1235. st = ic->streams[pkt->stream_index];
  1236. if (pkt->pts != AV_NOPTS_VALUE) {
  1237. end_time = av_rescale(pkt->pts, st->time_base.num * (int64_t)AV_TIME_BASE, st->time_base.den);
  1238. duration = end_time - st->start_time;
  1239. if (duration > 0) {
  1240. if (st->duration == AV_NOPTS_VALUE ||
  1241. st->duration < duration)
  1242. st->duration = duration;
  1243. }
  1244. }
  1245. av_free_packet(pkt);
  1246. }
  1247. /* estimate total duration */
  1248. end_time = MININT64;
  1249. for(i = 0;i < ic->nb_streams; i++) {
  1250. st = ic->streams[i];
  1251. if (st->duration != AV_NOPTS_VALUE) {
  1252. end_time1 = st->start_time + st->duration;
  1253. if (end_time1 > end_time)
  1254. end_time = end_time1;
  1255. }
  1256. }
  1257. /* update start_time (new stream may have been created, so we do
  1258. it at the end */
  1259. if (ic->start_time != AV_NOPTS_VALUE) {
  1260. for(i = 0; i < ic->nb_streams; i++) {
  1261. st = ic->streams[i];
  1262. if (st->start_time == AV_NOPTS_VALUE)
  1263. st->start_time = ic->start_time;
  1264. }
  1265. }
  1266. if (end_time != MININT64) {
  1267. /* put dummy values for duration if needed */
  1268. for(i = 0;i < ic->nb_streams; i++) {
  1269. st = ic->streams[i];
  1270. if (st->duration == AV_NOPTS_VALUE &&
  1271. st->start_time != AV_NOPTS_VALUE)
  1272. st->duration = end_time - st->start_time;
  1273. }
  1274. ic->duration = end_time - ic->start_time;
  1275. }
  1276. url_fseek(&ic->pb, 0, SEEK_SET);
  1277. }
  1278. static void av_estimate_timings(AVFormatContext *ic)
  1279. {
  1280. URLContext *h;
  1281. int64_t file_size;
  1282. /* get the file size, if possible */
  1283. if (ic->iformat->flags & AVFMT_NOFILE) {
  1284. file_size = 0;
  1285. } else {
  1286. h = url_fileno(&ic->pb);
  1287. file_size = url_filesize(h);
  1288. if (file_size < 0)
  1289. file_size = 0;
  1290. }
  1291. ic->file_size = file_size;
  1292. if (ic->iformat == &mpegps_demux) {
  1293. /* get accurate estimate from the PTSes */
  1294. av_estimate_timings_from_pts(ic);
  1295. } else if (av_has_timings(ic)) {
  1296. /* at least one components has timings - we use them for all
  1297. the components */
  1298. fill_all_stream_timings(ic);
  1299. } else {
  1300. /* less precise: use bit rate info */
  1301. av_estimate_timings_from_bit_rate(ic);
  1302. }
  1303. av_update_stream_timings(ic);
  1304. #if 0
  1305. {
  1306. int i;
  1307. AVStream *st;
  1308. for(i = 0;i < ic->nb_streams; i++) {
  1309. st = ic->streams[i];
  1310. printf("%d: start_time: %0.3f duration: %0.3f\n",
  1311. i, (double)st->start_time / AV_TIME_BASE,
  1312. (double)st->duration / AV_TIME_BASE);
  1313. }
  1314. printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
  1315. (double)ic->start_time / AV_TIME_BASE,
  1316. (double)ic->duration / AV_TIME_BASE,
  1317. ic->bit_rate / 1000);
  1318. }
  1319. #endif
  1320. }
  1321. static int has_codec_parameters(AVCodecContext *enc)
  1322. {
  1323. int val;
  1324. switch(enc->codec_type) {
  1325. case CODEC_TYPE_AUDIO:
  1326. val = enc->sample_rate;
  1327. break;
  1328. case CODEC_TYPE_VIDEO:
  1329. val = enc->width;
  1330. break;
  1331. default:
  1332. val = 1;
  1333. break;
  1334. }
  1335. return (val != 0);
  1336. }
  1337. static int try_decode_frame(AVStream *st, const uint8_t *data, int size)
  1338. {
  1339. int16_t *samples;
  1340. AVCodec *codec;
  1341. int got_picture, ret;
  1342. AVFrame picture;
  1343. codec = avcodec_find_decoder(st->codec.codec_id);
  1344. if (!codec)
  1345. return -1;
  1346. ret = avcodec_open(&st->codec, codec);
  1347. if (ret < 0)
  1348. return ret;
  1349. switch(st->codec.codec_type) {
  1350. case CODEC_TYPE_VIDEO:
  1351. ret = avcodec_decode_video(&st->codec, &picture,
  1352. &got_picture, (uint8_t *)data, size);
  1353. break;
  1354. case CODEC_TYPE_AUDIO:
  1355. samples = av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
  1356. if (!samples)
  1357. goto fail;
  1358. ret = avcodec_decode_audio(&st->codec, samples,
  1359. &got_picture, (uint8_t *)data, size);
  1360. av_free(samples);
  1361. break;
  1362. default:
  1363. break;
  1364. }
  1365. fail:
  1366. avcodec_close(&st->codec);
  1367. return ret;
  1368. }
  1369. /* absolute maximum size we read until we abort */
  1370. #define MAX_READ_SIZE 5000000
  1371. /* maximum duration until we stop analysing the stream */
  1372. #define MAX_STREAM_DURATION ((int)(AV_TIME_BASE * 1.0))
  1373. /**
  1374. * Read the beginning of a media file to get stream information. This
  1375. * is useful for file formats with no headers such as MPEG. This
  1376. * function also compute the real frame rate in case of mpeg2 repeat
  1377. * frame mode.
  1378. *
  1379. * @param ic media file handle
  1380. * @return >=0 if OK. AVERROR_xxx if error.
  1381. */
  1382. int av_find_stream_info(AVFormatContext *ic)
  1383. {
  1384. int i, count, ret, read_size;
  1385. AVStream *st;
  1386. AVPacket pkt1, *pkt;
  1387. AVPacketList *pktl=NULL, **ppktl;
  1388. count = 0;
  1389. read_size = 0;
  1390. ppktl = &ic->packet_buffer;
  1391. for(;;) {
  1392. /* check if one codec still needs to be handled */
  1393. for(i=0;i<ic->nb_streams;i++) {
  1394. st = ic->streams[i];
  1395. if (!has_codec_parameters(&st->codec))
  1396. break;
  1397. }
  1398. if (i == ic->nb_streams) {
  1399. /* NOTE: if the format has no header, then we need to read
  1400. some packets to get most of the streams, so we cannot
  1401. stop here */
  1402. if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
  1403. /* if we found the info for all the codecs, we can stop */
  1404. ret = count;
  1405. break;
  1406. }
  1407. } else {
  1408. /* we did not get all the codec info, but we read too much data */
  1409. if (read_size >= MAX_READ_SIZE) {
  1410. ret = count;
  1411. break;
  1412. }
  1413. }
  1414. /* NOTE: a new stream can be added there if no header in file
  1415. (AVFMTCTX_NOHEADER) */
  1416. ret = av_read_frame_internal(ic, &pkt1);
  1417. if (ret < 0) {
  1418. /* EOF or error */
  1419. ret = -1; /* we could not have all the codec parameters before EOF */
  1420. if ((ic->ctx_flags & AVFMTCTX_NOHEADER) &&
  1421. i == ic->nb_streams)
  1422. ret = 0;
  1423. break;
  1424. }
  1425. pktl = av_mallocz(sizeof(AVPacketList));
  1426. if (!pktl) {
  1427. ret = AVERROR_NOMEM;
  1428. break;
  1429. }
  1430. /* add the packet in the buffered packet list */
  1431. *ppktl = pktl;
  1432. ppktl = &pktl->next;
  1433. pkt = &pktl->pkt;
  1434. *pkt = pkt1;
  1435. /* duplicate the packet */
  1436. if (av_dup_packet(pkt) < 0) {
  1437. ret = AVERROR_NOMEM;
  1438. break;
  1439. }
  1440. read_size += pkt->size;
  1441. st = ic->streams[pkt->stream_index];
  1442. st->codec_info_duration += pkt->duration;
  1443. if (pkt->duration != 0)
  1444. st->codec_info_nb_frames++;
  1445. /* if still no information, we try to open the codec and to
  1446. decompress the frame. We try to avoid that in most cases as
  1447. it takes longer and uses more memory. For MPEG4, we need to
  1448. decompress for Quicktime. */
  1449. if (!has_codec_parameters(&st->codec) &&
  1450. (st->codec.codec_id == CODEC_ID_FLV1 ||
  1451. st->codec.codec_id == CODEC_ID_H264 ||
  1452. st->codec.codec_id == CODEC_ID_H263 ||
  1453. st->codec.codec_id == CODEC_ID_VORBIS ||
  1454. (st->codec.codec_id == CODEC_ID_MPEG4 && !st->need_parsing)))
  1455. try_decode_frame(st, pkt->data, pkt->size);
  1456. if (st->codec_info_duration >= MAX_STREAM_DURATION) {
  1457. break;
  1458. }
  1459. count++;
  1460. }
  1461. /* set real frame rate info */
  1462. for(i=0;i<ic->nb_streams;i++) {
  1463. st = ic->streams[i];
  1464. if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
  1465. /* compute the real frame rate for telecine */
  1466. if ((st->codec.codec_id == CODEC_ID_MPEG1VIDEO ||
  1467. st->codec.codec_id == CODEC_ID_MPEG2VIDEO) &&
  1468. st->codec.sub_id == 2) {
  1469. if (st->codec_info_nb_frames >= 20) {
  1470. float coded_frame_rate, est_frame_rate;
  1471. est_frame_rate = ((double)st->codec_info_nb_frames * AV_TIME_BASE) /
  1472. (double)st->codec_info_duration ;
  1473. coded_frame_rate = (double)st->codec.frame_rate /
  1474. (double)st->codec.frame_rate_base;
  1475. #if 0
  1476. printf("telecine: coded_frame_rate=%0.3f est_frame_rate=%0.3f\n",
  1477. coded_frame_rate, est_frame_rate);
  1478. #endif
  1479. /* if we detect that it could be a telecine, we
  1480. signal it. It would be better to do it at a
  1481. higher level as it can change in a film */
  1482. if (coded_frame_rate >= 24.97 &&
  1483. (est_frame_rate >= 23.5 && est_frame_rate < 24.5)) {
  1484. st->r_frame_rate = 24024;
  1485. st->r_frame_rate_base = 1001;
  1486. }
  1487. }
  1488. }
  1489. /* if no real frame rate, use the codec one */
  1490. if (!st->r_frame_rate){
  1491. st->r_frame_rate = st->codec.frame_rate;
  1492. st->r_frame_rate_base = st->codec.frame_rate_base;
  1493. }
  1494. }
  1495. }
  1496. av_estimate_timings(ic);
  1497. #if 0
  1498. /* correct DTS for b frame streams with no timestamps */
  1499. for(i=0;i<ic->nb_streams;i++) {
  1500. st = ic->streams[i];
  1501. if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
  1502. if(b-frames){
  1503. ppktl = &ic->packet_buffer;
  1504. while(ppkt1){
  1505. if(ppkt1->stream_index != i)
  1506. continue;
  1507. if(ppkt1->pkt->dts < 0)
  1508. break;
  1509. if(ppkt1->pkt->pts != AV_NOPTS_VALUE)
  1510. break;
  1511. ppkt1->pkt->dts -= delta;
  1512. ppkt1= ppkt1->next;
  1513. }
  1514. if(ppkt1)
  1515. continue;
  1516. st->cur_dts -= delta;
  1517. }
  1518. }
  1519. }
  1520. #endif
  1521. return ret;
  1522. }
  1523. /*******************************************************/
  1524. /**
  1525. * start playing a network based stream (e.g. RTSP stream) at the
  1526. * current position
  1527. */
  1528. int av_read_play(AVFormatContext *s)
  1529. {
  1530. if (!s->iformat->read_play)
  1531. return AVERROR_NOTSUPP;
  1532. return s->iformat->read_play(s);
  1533. }
  1534. /**
  1535. * pause a network based stream (e.g. RTSP stream). Use av_read_play()
  1536. * to resume it.
  1537. */
  1538. int av_read_pause(AVFormatContext *s)
  1539. {
  1540. if (!s->iformat->read_pause)
  1541. return AVERROR_NOTSUPP;
  1542. return s->iformat->read_pause(s);
  1543. }
  1544. /**
  1545. * Close a media file (but not its codecs)
  1546. *
  1547. * @param s media file handle
  1548. */
  1549. void av_close_input_file(AVFormatContext *s)
  1550. {
  1551. int i, must_open_file;
  1552. AVStream *st;
  1553. /* free previous packet */
  1554. if (s->cur_st && s->cur_st->parser)
  1555. av_free_packet(&s->cur_pkt);
  1556. if (s->iformat->read_close)
  1557. s->iformat->read_close(s);
  1558. for(i=0;i<s->nb_streams;i++) {
  1559. /* free all data in a stream component */
  1560. st = s->streams[i];
  1561. if (st->parser) {
  1562. av_parser_close(st->parser);
  1563. }
  1564. av_free(st->index_entries);
  1565. av_free(st);
  1566. }
  1567. flush_packet_queue(s);
  1568. must_open_file = 1;
  1569. if (s->iformat->flags & AVFMT_NOFILE) {
  1570. must_open_file = 0;
  1571. }
  1572. if (must_open_file) {
  1573. url_fclose(&s->pb);
  1574. }
  1575. av_freep(&s->priv_data);
  1576. av_free(s);
  1577. }
  1578. /**
  1579. * Add a new stream to a media file. Can only be called in the
  1580. * read_header function. If the flag AVFMTCTX_NOHEADER is in the
  1581. * format context, then new streams can be added in read_packet too.
  1582. *
  1583. *
  1584. * @param s media file handle
  1585. * @param id file format dependent stream id
  1586. */
  1587. AVStream *av_new_stream(AVFormatContext *s, int id)
  1588. {
  1589. AVStream *st;
  1590. if (s->nb_streams >= MAX_STREAMS)
  1591. return NULL;
  1592. st = av_mallocz(sizeof(AVStream));
  1593. if (!st)
  1594. return NULL;
  1595. avcodec_get_context_defaults(&st->codec);
  1596. if (s->iformat) {
  1597. /* no default bitrate if decoding */
  1598. st->codec.bit_rate = 0;
  1599. }
  1600. st->index = s->nb_streams;
  1601. st->id = id;
  1602. st->start_time = AV_NOPTS_VALUE;
  1603. st->duration = AV_NOPTS_VALUE;
  1604. st->cur_dts = AV_NOPTS_VALUE;
  1605. /* default pts settings is MPEG like */
  1606. av_set_pts_info(st, 33, 1, 90000);
  1607. st->last_IP_pts = AV_NOPTS_VALUE;
  1608. s->streams[s->nb_streams++] = st;
  1609. return st;
  1610. }
  1611. /************************************************************/
  1612. /* output media file */
  1613. int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
  1614. {
  1615. int ret;
  1616. if (s->oformat->priv_data_size > 0) {
  1617. s->priv_data = av_mallocz(s->oformat->priv_data_size);
  1618. if (!s->priv_data)
  1619. return AVERROR_NOMEM;
  1620. } else
  1621. s->priv_data = NULL;
  1622. if (s->oformat->set_parameters) {
  1623. ret = s->oformat->set_parameters(s, ap);
  1624. if (ret < 0)
  1625. return ret;
  1626. }
  1627. return 0;
  1628. }
  1629. /**
  1630. * allocate the stream private data and write the stream header to an
  1631. * output media file
  1632. *
  1633. * @param s media file handle
  1634. * @return 0 if OK. AVERROR_xxx if error.
  1635. */
  1636. int av_write_header(AVFormatContext *s)
  1637. {
  1638. int ret, i;
  1639. AVStream *st;
  1640. ret = s->oformat->write_header(s);
  1641. if (ret < 0)
  1642. return ret;
  1643. /* init PTS generation */
  1644. for(i=0;i<s->nb_streams;i++) {
  1645. st = s->streams[i];
  1646. switch (st->codec.codec_type) {
  1647. case CODEC_TYPE_AUDIO:
  1648. av_frac_init(&st->pts, 0, 0,
  1649. (int64_t)st->time_base.num * st->codec.sample_rate);
  1650. break;
  1651. case CODEC_TYPE_VIDEO:
  1652. av_frac_init(&st->pts, 0, 0,
  1653. (int64_t)st->time_base.num * st->codec.frame_rate);
  1654. break;
  1655. default:
  1656. break;
  1657. }
  1658. }
  1659. return 0;
  1660. }
  1661. //FIXME merge with compute_pkt_fields
  1662. static void compute_pkt_fields2(AVStream *st, AVPacket *pkt){
  1663. int b_frames = FFMAX(st->codec.has_b_frames, st->codec.max_b_frames);
  1664. int num, den, frame_size;
  1665. // av_log(NULL, AV_LOG_DEBUG, "av_write_frame: pts:%lld dts:%lld cur_dts:%lld b:%d size:%d st:%d\n", pkt->pts, pkt->dts, st->cur_dts, b_frames, pkt->size, pkt->stream_index);
  1666. /* if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
  1667. return -1;*/
  1668. if(pkt->pts != AV_NOPTS_VALUE)
  1669. pkt->pts = av_rescale(pkt->pts, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
  1670. if(pkt->dts != AV_NOPTS_VALUE)
  1671. pkt->dts = av_rescale(pkt->dts, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
  1672. /* duration field */
  1673. pkt->duration = av_rescale(pkt->duration, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
  1674. if (pkt->duration == 0) {
  1675. compute_frame_duration(&num, &den, st, NULL, pkt);
  1676. if (den && num) {
  1677. pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
  1678. }
  1679. }
  1680. //XXX/FIXME this is a temporary hack until all encoders output pts
  1681. if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !b_frames){
  1682. pkt->dts=
  1683. // pkt->pts= st->cur_dts;
  1684. pkt->pts= st->pts.val;
  1685. }
  1686. //calculate dts from pts
  1687. if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE){
  1688. if(b_frames){
  1689. if(st->last_IP_pts == AV_NOPTS_VALUE){
  1690. st->last_IP_pts= -pkt->duration;
  1691. }
  1692. if(st->last_IP_pts < pkt->pts){
  1693. pkt->dts= st->last_IP_pts;
  1694. st->last_IP_pts= pkt->pts;
  1695. }else
  1696. pkt->dts= pkt->pts;
  1697. }else
  1698. pkt->dts= pkt->pts;
  1699. }
  1700. // av_log(NULL, AV_LOG_DEBUG, "av_write_frame: pts2:%lld dts2:%lld\n", pkt->pts, pkt->dts);
  1701. st->cur_dts= pkt->dts;
  1702. st->pts.val= pkt->dts;
  1703. /* update pts */
  1704. switch (st->codec.codec_type) {
  1705. case CODEC_TYPE_AUDIO:
  1706. frame_size = get_audio_frame_size(&st->codec, pkt->size);
  1707. /* HACK/FIXME, we skip the initial 0-size packets as they are most likely equal to the encoder delay,
  1708. but it would be better if we had the real timestamps from the encoder */
  1709. if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) {
  1710. av_frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
  1711. }
  1712. break;
  1713. case CODEC_TYPE_VIDEO:
  1714. av_frac_add(&st->pts, (int64_t)st->time_base.den * st->codec.frame_rate_base);
  1715. break;
  1716. default:
  1717. break;
  1718. }
  1719. }
  1720. static void truncate_ts(AVStream *st, AVPacket *pkt){
  1721. int64_t pts_mask = (2LL << (st->pts_wrap_bits-1)) - 1;
  1722. if(pkt->dts < 0)
  1723. pkt->dts= 0; //this happens for low_delay=0 and b frames, FIXME, needs further invstigation about what we should do here
  1724. pkt->pts &= pts_mask;
  1725. pkt->dts &= pts_mask;
  1726. }
  1727. /**
  1728. * Write a packet to an output media file. The packet shall contain
  1729. * one audio or video frame.
  1730. *
  1731. * @param s media file handle
  1732. * @param pkt the packet, which contains the stream_index, buf/buf_size, dts/pts, ...
  1733. * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
  1734. */
  1735. int av_write_frame(AVFormatContext *s, AVPacket *pkt)
  1736. {
  1737. compute_pkt_fields2(s->streams[pkt->stream_index], pkt);
  1738. truncate_ts(s->streams[pkt->stream_index], pkt);
  1739. return s->oformat->write_packet(s, pkt);
  1740. }
  1741. /**
  1742. * Writes a packet to an output media file ensuring correct interleaving.
  1743. * The packet shall contain one audio or video frame.
  1744. * If the packets are already correctly interleaved the application should
  1745. * call av_write_frame() instead as its slightly faster, its also important
  1746. * to keep in mind that non interlaved input will need huge amounts
  1747. * of memory to interleave with this, so its prefereable to interleave at the
  1748. * demuxer level
  1749. *
  1750. * @param s media file handle
  1751. * @param pkt the packet, which contains the stream_index, buf/buf_size, dts/pts, ...
  1752. * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
  1753. */
  1754. int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){
  1755. AVPacketList *pktl, **next_point, *this_pktl;
  1756. int stream_count=0;
  1757. int streams[MAX_STREAMS];
  1758. AVStream *st= s->streams[ pkt->stream_index];
  1759. compute_pkt_fields2(st, pkt);
  1760. if(pkt->dts == AV_NOPTS_VALUE)
  1761. return -1;
  1762. assert(pkt->destruct != av_destruct_packet); //FIXME
  1763. this_pktl = av_mallocz(sizeof(AVPacketList));
  1764. this_pktl->pkt= *pkt;
  1765. av_dup_packet(&this_pktl->pkt);
  1766. next_point = &s->packet_buffer;
  1767. while(*next_point){
  1768. AVStream *st2= s->streams[ (*next_point)->pkt.stream_index];
  1769. int64_t left= st2->time_base.num * st ->time_base.den;
  1770. int64_t right= st ->time_base.num * st2->time_base.den;
  1771. if((*next_point)->pkt.dts * left > pkt->dts * right) //FIXME this can overflow
  1772. break;
  1773. next_point= &(*next_point)->next;
  1774. }
  1775. this_pktl->next= *next_point;
  1776. *next_point= this_pktl;
  1777. memset(streams, 0, sizeof(streams));
  1778. pktl= s->packet_buffer;
  1779. while(pktl){
  1780. //av_log(s, AV_LOG_DEBUG, "show st:%d dts:%lld\n", pktl->pkt.stream_index, pktl->pkt.dts);
  1781. if(streams[ pktl->pkt.stream_index ] == 0)
  1782. stream_count++;
  1783. streams[ pktl->pkt.stream_index ]++;
  1784. pktl= pktl->next;
  1785. }
  1786. while(s->nb_streams == stream_count){
  1787. int ret;
  1788. pktl= s->packet_buffer;
  1789. //av_log(s, AV_LOG_DEBUG, "write st:%d dts:%lld\n", pktl->pkt.stream_index, pktl->pkt.dts);
  1790. truncate_ts(s->streams[pktl->pkt.stream_index], &pktl->pkt);
  1791. ret= s->oformat->write_packet(s, &pktl->pkt);
  1792. s->packet_buffer= pktl->next;
  1793. if((--streams[ pktl->pkt.stream_index ]) == 0)
  1794. stream_count--;
  1795. av_free_packet(&pktl->pkt);
  1796. av_freep(&pktl);
  1797. if(ret<0)
  1798. return ret;
  1799. }
  1800. return 0;
  1801. }
  1802. /**
  1803. * write the stream trailer to an output media file and and free the
  1804. * file private data.
  1805. *
  1806. * @param s media file handle
  1807. * @return 0 if OK. AVERROR_xxx if error. */
  1808. int av_write_trailer(AVFormatContext *s)
  1809. {
  1810. int ret;
  1811. while(s->packet_buffer){
  1812. int ret;
  1813. AVPacketList *pktl= s->packet_buffer;
  1814. //av_log(s, AV_LOG_DEBUG, "write_trailer st:%d dts:%lld\n", pktl->pkt.stream_index, pktl->pkt.dts);
  1815. truncate_ts(s->streams[pktl->pkt.stream_index], &pktl->pkt);
  1816. ret= s->oformat->write_packet(s, &pktl->pkt);
  1817. s->packet_buffer= pktl->next;
  1818. av_free_packet(&pktl->pkt);
  1819. av_freep(&pktl);
  1820. if(ret<0)
  1821. return ret;
  1822. }
  1823. ret = s->oformat->write_trailer(s);
  1824. av_freep(&s->priv_data);
  1825. return ret;
  1826. }
  1827. /* "user interface" functions */
  1828. void dump_format(AVFormatContext *ic,
  1829. int index,
  1830. const char *url,
  1831. int is_output)
  1832. {
  1833. int i, flags;
  1834. char buf[256];
  1835. av_log(NULL, AV_LOG_DEBUG, "%s #%d, %s, %s '%s':\n",
  1836. is_output ? "Output" : "Input",
  1837. index,
  1838. is_output ? ic->oformat->name : ic->iformat->name,
  1839. is_output ? "to" : "from", url);
  1840. if (!is_output) {
  1841. av_log(NULL, AV_LOG_DEBUG, " Duration: ");
  1842. if (ic->duration != AV_NOPTS_VALUE) {
  1843. int hours, mins, secs, us;
  1844. secs = ic->duration / AV_TIME_BASE;
  1845. us = ic->duration % AV_TIME_BASE;
  1846. mins = secs / 60;
  1847. secs %= 60;
  1848. hours = mins / 60;
  1849. mins %= 60;
  1850. av_log(NULL, AV_LOG_DEBUG, "%02d:%02d:%02d.%01d", hours, mins, secs,
  1851. (10 * us) / AV_TIME_BASE);
  1852. } else {
  1853. av_log(NULL, AV_LOG_DEBUG, "N/A");
  1854. }
  1855. av_log(NULL, AV_LOG_DEBUG, ", bitrate: ");
  1856. if (ic->bit_rate) {
  1857. av_log(NULL, AV_LOG_DEBUG,"%d kb/s", ic->bit_rate / 1000);
  1858. } else {
  1859. av_log(NULL, AV_LOG_DEBUG, "N/A");
  1860. }
  1861. av_log(NULL, AV_LOG_DEBUG, "\n");
  1862. }
  1863. for(i=0;i<ic->nb_streams;i++) {
  1864. AVStream *st = ic->streams[i];
  1865. avcodec_string(buf, sizeof(buf), &st->codec, is_output);
  1866. av_log(NULL, AV_LOG_DEBUG, " Stream #%d.%d", index, i);
  1867. /* the pid is an important information, so we display it */
  1868. /* XXX: add a generic system */
  1869. if (is_output)
  1870. flags = ic->oformat->flags;
  1871. else
  1872. flags = ic->iformat->flags;
  1873. if (flags & AVFMT_SHOW_IDS) {
  1874. av_log(NULL, AV_LOG_DEBUG, "[0x%x]", st->id);
  1875. }
  1876. av_log(NULL, AV_LOG_DEBUG, ": %s\n", buf);
  1877. }
  1878. }
  1879. typedef struct {
  1880. const char *abv;
  1881. int width, height;
  1882. int frame_rate, frame_rate_base;
  1883. } AbvEntry;
  1884. static AbvEntry frame_abvs[] = {
  1885. { "ntsc", 720, 480, 30000, 1001 },
  1886. { "pal", 720, 576, 25, 1 },
  1887. { "qntsc", 352, 240, 30000, 1001 }, /* VCD compliant ntsc */
  1888. { "qpal", 352, 288, 25, 1 }, /* VCD compliant pal */
  1889. { "sntsc", 640, 480, 30000, 1001 }, /* square pixel ntsc */
  1890. { "spal", 768, 576, 25, 1 }, /* square pixel pal */
  1891. { "film", 352, 240, 24, 1 },
  1892. { "ntsc-film", 352, 240, 24000, 1001 },
  1893. { "sqcif", 128, 96, 0, 0 },
  1894. { "qcif", 176, 144, 0, 0 },
  1895. { "cif", 352, 288, 0, 0 },
  1896. { "4cif", 704, 576, 0, 0 },
  1897. };
  1898. int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
  1899. {
  1900. int i;
  1901. int n = sizeof(frame_abvs) / sizeof(AbvEntry);
  1902. const char *p;
  1903. int frame_width = 0, frame_height = 0;
  1904. for(i=0;i<n;i++) {
  1905. if (!strcmp(frame_abvs[i].abv, str)) {
  1906. frame_width = frame_abvs[i].width;
  1907. frame_height = frame_abvs[i].height;
  1908. break;
  1909. }
  1910. }
  1911. if (i == n) {
  1912. p = str;
  1913. frame_width = strtol(p, (char **)&p, 10);
  1914. if (*p)
  1915. p++;
  1916. frame_height = strtol(p, (char **)&p, 10);
  1917. }
  1918. if (frame_width <= 0 || frame_height <= 0)
  1919. return -1;
  1920. *width_ptr = frame_width;
  1921. *height_ptr = frame_height;
  1922. return 0;
  1923. }
  1924. int parse_frame_rate(int *frame_rate, int *frame_rate_base, const char *arg)
  1925. {
  1926. int i;
  1927. char* cp;
  1928. /* First, we check our abbreviation table */
  1929. for (i = 0; i < sizeof(frame_abvs)/sizeof(*frame_abvs); ++i)
  1930. if (!strcmp(frame_abvs[i].abv, arg)) {
  1931. *frame_rate = frame_abvs[i].frame_rate;
  1932. *frame_rate_base = frame_abvs[i].frame_rate_base;
  1933. return 0;
  1934. }
  1935. /* Then, we try to parse it as fraction */
  1936. cp = strchr(arg, '/');
  1937. if (cp) {
  1938. char* cpp;
  1939. *frame_rate = strtol(arg, &cpp, 10);
  1940. if (cpp != arg || cpp == cp)
  1941. *frame_rate_base = strtol(cp+1, &cpp, 10);
  1942. else
  1943. *frame_rate = 0;
  1944. }
  1945. else {
  1946. /* Finally we give up and parse it as double */
  1947. *frame_rate_base = DEFAULT_FRAME_RATE_BASE; //FIXME use av_d2q()
  1948. *frame_rate = (int)(strtod(arg, 0) * (*frame_rate_base) + 0.5);
  1949. }
  1950. if (!*frame_rate || !*frame_rate_base)
  1951. return -1;
  1952. else
  1953. return 0;
  1954. }
  1955. /* Syntax:
  1956. * - If not a duration:
  1957. * [{YYYY-MM-DD|YYYYMMDD}]{T| }{HH[:MM[:SS[.m...]]][Z]|HH[MM[SS[.m...]]][Z]}
  1958. * Time is localtime unless Z is suffixed to the end. In this case GMT
  1959. * Return the date in micro seconds since 1970
  1960. * - If duration:
  1961. * HH[:MM[:SS[.m...]]]
  1962. * S+[.m...]
  1963. */
  1964. int64_t parse_date(const char *datestr, int duration)
  1965. {
  1966. const char *p;
  1967. int64_t t;
  1968. struct tm dt;
  1969. int i;
  1970. static const char *date_fmt[] = {
  1971. "%Y-%m-%d",
  1972. "%Y%m%d",
  1973. };
  1974. static const char *time_fmt[] = {
  1975. "%H:%M:%S",
  1976. "%H%M%S",
  1977. };
  1978. const char *q;
  1979. int is_utc, len;
  1980. char lastch;
  1981. #undef time
  1982. time_t now = time(0);
  1983. len = strlen(datestr);
  1984. if (len > 0)
  1985. lastch = datestr[len - 1];
  1986. else
  1987. lastch = '\0';
  1988. is_utc = (lastch == 'z' || lastch == 'Z');
  1989. memset(&dt, 0, sizeof(dt));
  1990. p = datestr;
  1991. q = NULL;
  1992. if (!duration) {
  1993. for (i = 0; i < sizeof(date_fmt) / sizeof(date_fmt[0]); i++) {
  1994. q = small_strptime(p, date_fmt[i], &dt);
  1995. if (q) {
  1996. break;
  1997. }
  1998. }
  1999. if (!q) {
  2000. if (is_utc) {
  2001. dt = *gmtime(&now);
  2002. } else {
  2003. dt = *localtime(&now);
  2004. }
  2005. dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
  2006. } else {
  2007. p = q;
  2008. }
  2009. if (*p == 'T' || *p == 't' || *p == ' ')
  2010. p++;
  2011. for (i = 0; i < sizeof(time_fmt) / sizeof(time_fmt[0]); i++) {
  2012. q = small_strptime(p, time_fmt[i], &dt);
  2013. if (q) {
  2014. break;
  2015. }
  2016. }
  2017. } else {
  2018. q = small_strptime(p, time_fmt[0], &dt);
  2019. if (!q) {
  2020. dt.tm_sec = strtol(p, (char **)&q, 10);
  2021. dt.tm_min = 0;
  2022. dt.tm_hour = 0;
  2023. }
  2024. }
  2025. /* Now we have all the fields that we can get */
  2026. if (!q) {
  2027. if (duration)
  2028. return 0;
  2029. else
  2030. return now * int64_t_C(1000000);
  2031. }
  2032. if (duration) {
  2033. t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
  2034. } else {
  2035. dt.tm_isdst = -1; /* unknown */
  2036. if (is_utc) {
  2037. t = mktimegm(&dt);
  2038. } else {
  2039. t = mktime(&dt);
  2040. }
  2041. }
  2042. t *= 1000000;
  2043. if (*q == '.') {
  2044. int val, n;
  2045. q++;
  2046. for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
  2047. if (!isdigit(*q))
  2048. break;
  2049. val += n * (*q - '0');
  2050. }
  2051. t += val;
  2052. }
  2053. return t;
  2054. }
  2055. /* syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done. Return
  2056. 1 if found */
  2057. int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
  2058. {
  2059. const char *p;
  2060. char tag[128], *q;
  2061. p = info;
  2062. if (*p == '?')
  2063. p++;
  2064. for(;;) {
  2065. q = tag;
  2066. while (*p != '\0' && *p != '=' && *p != '&') {
  2067. if ((q - tag) < sizeof(tag) - 1)
  2068. *q++ = *p;
  2069. p++;
  2070. }
  2071. *q = '\0';
  2072. q = arg;
  2073. if (*p == '=') {
  2074. p++;
  2075. while (*p != '&' && *p != '\0') {
  2076. if ((q - arg) < arg_size - 1) {
  2077. if (*p == '+')
  2078. *q++ = ' ';
  2079. else
  2080. *q++ = *p;
  2081. }
  2082. p++;
  2083. }
  2084. *q = '\0';
  2085. }
  2086. if (!strcmp(tag, tag1))
  2087. return 1;
  2088. if (*p != '&')
  2089. break;
  2090. p++;
  2091. }
  2092. return 0;
  2093. }
  2094. /* Return in 'buf' the path with '%d' replaced by number. Also handles
  2095. the '%0nd' format where 'n' is the total number of digits and
  2096. '%%'. Return 0 if OK, and -1 if format error */
  2097. int get_frame_filename(char *buf, int buf_size,
  2098. const char *path, int number)
  2099. {
  2100. const char *p;
  2101. char *q, buf1[20], c;
  2102. int nd, len, percentd_found;
  2103. q = buf;
  2104. p = path;
  2105. percentd_found = 0;
  2106. for(;;) {
  2107. c = *p++;
  2108. if (c == '\0')
  2109. break;
  2110. if (c == '%') {
  2111. do {
  2112. nd = 0;
  2113. while (isdigit(*p)) {
  2114. nd = nd * 10 + *p++ - '0';
  2115. }
  2116. c = *p++;
  2117. } while (isdigit(c));
  2118. switch(c) {
  2119. case '%':
  2120. goto addchar;
  2121. case 'd':
  2122. if (percentd_found)
  2123. goto fail;
  2124. percentd_found = 1;
  2125. snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
  2126. len = strlen(buf1);
  2127. if ((q - buf + len) > buf_size - 1)
  2128. goto fail;
  2129. memcpy(q, buf1, len);
  2130. q += len;
  2131. break;
  2132. default:
  2133. goto fail;
  2134. }
  2135. } else {
  2136. addchar:
  2137. if ((q - buf) < buf_size - 1)
  2138. *q++ = c;
  2139. }
  2140. }
  2141. if (!percentd_found)
  2142. goto fail;
  2143. *q = '\0';
  2144. return 0;
  2145. fail:
  2146. *q = '\0';
  2147. return -1;
  2148. }
  2149. /**
  2150. * Print nice hexa dump of a buffer
  2151. * @param f stream for output
  2152. * @param buf buffer
  2153. * @param size buffer size
  2154. */
  2155. void av_hex_dump(FILE *f, uint8_t *buf, int size)
  2156. {
  2157. int len, i, j, c;
  2158. for(i=0;i<size;i+=16) {
  2159. len = size - i;
  2160. if (len > 16)
  2161. len = 16;
  2162. fprintf(f, "%08x ", i);
  2163. for(j=0;j<16;j++) {
  2164. if (j < len)
  2165. fprintf(f, " %02x", buf[i+j]);
  2166. else
  2167. fprintf(f, " ");
  2168. }
  2169. fprintf(f, " ");
  2170. for(j=0;j<len;j++) {
  2171. c = buf[i+j];
  2172. if (c < ' ' || c > '~')
  2173. c = '.';
  2174. fprintf(f, "%c", c);
  2175. }
  2176. fprintf(f, "\n");
  2177. }
  2178. }
  2179. /**
  2180. * Print on 'f' a nice dump of a packet
  2181. * @param f stream for output
  2182. * @param pkt packet to dump
  2183. * @param dump_payload true if the payload must be displayed too
  2184. */
  2185. void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload)
  2186. {
  2187. fprintf(f, "stream #%d:\n", pkt->stream_index);
  2188. fprintf(f, " keyframe=%d\n", ((pkt->flags & PKT_FLAG_KEY) != 0));
  2189. fprintf(f, " duration=%0.3f\n", (double)pkt->duration / AV_TIME_BASE);
  2190. /* DTS is _always_ valid after av_read_frame() */
  2191. fprintf(f, " dts=");
  2192. if (pkt->dts == AV_NOPTS_VALUE)
  2193. fprintf(f, "N/A");
  2194. else
  2195. fprintf(f, "%0.3f", (double)pkt->dts / AV_TIME_BASE);
  2196. /* PTS may be not known if B frames are present */
  2197. fprintf(f, " pts=");
  2198. if (pkt->pts == AV_NOPTS_VALUE)
  2199. fprintf(f, "N/A");
  2200. else
  2201. fprintf(f, "%0.3f", (double)pkt->pts / AV_TIME_BASE);
  2202. fprintf(f, "\n");
  2203. fprintf(f, " size=%d\n", pkt->size);
  2204. if (dump_payload)
  2205. av_hex_dump(f, pkt->data, pkt->size);
  2206. }
  2207. void url_split(char *proto, int proto_size,
  2208. char *hostname, int hostname_size,
  2209. int *port_ptr,
  2210. char *path, int path_size,
  2211. const char *url)
  2212. {
  2213. const char *p;
  2214. char *q;
  2215. int port;
  2216. port = -1;
  2217. p = url;
  2218. q = proto;
  2219. while (*p != ':' && *p != '\0') {
  2220. if ((q - proto) < proto_size - 1)
  2221. *q++ = *p;
  2222. p++;
  2223. }
  2224. if (proto_size > 0)
  2225. *q = '\0';
  2226. if (*p == '\0') {
  2227. if (proto_size > 0)
  2228. proto[0] = '\0';
  2229. if (hostname_size > 0)
  2230. hostname[0] = '\0';
  2231. p = url;
  2232. } else {
  2233. p++;
  2234. if (*p == '/')
  2235. p++;
  2236. if (*p == '/')
  2237. p++;
  2238. q = hostname;
  2239. while (*p != ':' && *p != '/' && *p != '?' && *p != '\0') {
  2240. if ((q - hostname) < hostname_size - 1)
  2241. *q++ = *p;
  2242. p++;
  2243. }
  2244. if (hostname_size > 0)
  2245. *q = '\0';
  2246. if (*p == ':') {
  2247. p++;
  2248. port = strtoul(p, (char **)&p, 10);
  2249. }
  2250. }
  2251. if (port_ptr)
  2252. *port_ptr = port;
  2253. pstrcpy(path, path_size, p);
  2254. }
  2255. /**
  2256. * Set the pts for a given stream
  2257. * @param s stream
  2258. * @param pts_wrap_bits number of bits effectively used by the pts
  2259. * (used for wrap control, 33 is the value for MPEG)
  2260. * @param pts_num numerator to convert to seconds (MPEG: 1)
  2261. * @param pts_den denominator to convert to seconds (MPEG: 90000)
  2262. */
  2263. void av_set_pts_info(AVStream *s, int pts_wrap_bits,
  2264. int pts_num, int pts_den)
  2265. {
  2266. s->pts_wrap_bits = pts_wrap_bits;
  2267. s->time_base.num = pts_num;
  2268. s->time_base.den = pts_den;
  2269. }
  2270. /* fraction handling */
  2271. /**
  2272. * f = val + (num / den) + 0.5. 'num' is normalized so that it is such
  2273. * as 0 <= num < den.
  2274. *
  2275. * @param f fractional number
  2276. * @param val integer value
  2277. * @param num must be >= 0
  2278. * @param den must be >= 1
  2279. */
  2280. void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
  2281. {
  2282. num += (den >> 1);
  2283. if (num >= den) {
  2284. val += num / den;
  2285. num = num % den;
  2286. }
  2287. f->val = val;
  2288. f->num = num;
  2289. f->den = den;
  2290. }
  2291. /* set f to (val + 0.5) */
  2292. void av_frac_set(AVFrac *f, int64_t val)
  2293. {
  2294. f->val = val;
  2295. f->num = f->den >> 1;
  2296. }
  2297. /**
  2298. * Fractionnal addition to f: f = f + (incr / f->den)
  2299. *
  2300. * @param f fractional number
  2301. * @param incr increment, can be positive or negative
  2302. */
  2303. void av_frac_add(AVFrac *f, int64_t incr)
  2304. {
  2305. int64_t num, den;
  2306. num = f->num + incr;
  2307. den = f->den;
  2308. if (num < 0) {
  2309. f->val += num / den;
  2310. num = num % den;
  2311. if (num < 0) {
  2312. num += den;
  2313. f->val--;
  2314. }
  2315. } else if (num >= den) {
  2316. f->val += num / den;
  2317. num = num % den;
  2318. }
  2319. f->num = num;
  2320. }
  2321. /**
  2322. * register a new image format
  2323. * @param img_fmt Image format descriptor
  2324. */
  2325. void av_register_image_format(AVImageFormat *img_fmt)
  2326. {
  2327. AVImageFormat **p;
  2328. p = &first_image_format;
  2329. while (*p != NULL) p = &(*p)->next;
  2330. *p = img_fmt;
  2331. img_fmt->next = NULL;
  2332. }
  2333. /* guess image format */
  2334. AVImageFormat *av_probe_image_format(AVProbeData *pd)
  2335. {
  2336. AVImageFormat *fmt1, *fmt;
  2337. int score, score_max;
  2338. fmt = NULL;
  2339. score_max = 0;
  2340. for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
  2341. if (fmt1->img_probe) {
  2342. score = fmt1->img_probe(pd);
  2343. if (score > score_max) {
  2344. score_max = score;
  2345. fmt = fmt1;
  2346. }
  2347. }
  2348. }
  2349. return fmt;
  2350. }
  2351. AVImageFormat *guess_image_format(const char *filename)
  2352. {
  2353. AVImageFormat *fmt1;
  2354. for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
  2355. if (fmt1->extensions && match_ext(filename, fmt1->extensions))
  2356. return fmt1;
  2357. }
  2358. return NULL;
  2359. }
  2360. /**
  2361. * Read an image from a stream.
  2362. * @param gb byte stream containing the image
  2363. * @param fmt image format, NULL if probing is required
  2364. */
  2365. int av_read_image(ByteIOContext *pb, const char *filename,
  2366. AVImageFormat *fmt,
  2367. int (*alloc_cb)(void *, AVImageInfo *info), void *opaque)
  2368. {
  2369. char buf[PROBE_BUF_SIZE];
  2370. AVProbeData probe_data, *pd = &probe_data;
  2371. offset_t pos;
  2372. int ret;
  2373. if (!fmt) {
  2374. pd->filename = filename;
  2375. pd->buf = buf;
  2376. pos = url_ftell(pb);
  2377. pd->buf_size = get_buffer(pb, buf, PROBE_BUF_SIZE);
  2378. url_fseek(pb, pos, SEEK_SET);
  2379. fmt = av_probe_image_format(pd);
  2380. }
  2381. if (!fmt)
  2382. return AVERROR_NOFMT;
  2383. ret = fmt->img_read(pb, alloc_cb, opaque);
  2384. return ret;
  2385. }
  2386. /**
  2387. * Write an image to a stream.
  2388. * @param pb byte stream for the image output
  2389. * @param fmt image format
  2390. * @param img image data and informations
  2391. */
  2392. int av_write_image(ByteIOContext *pb, AVImageFormat *fmt, AVImageInfo *img)
  2393. {
  2394. return fmt->img_write(pb, img);
  2395. }