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.

2274 lines
62KB

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