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.

2526 lines
70KB

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