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.

2766 lines
78KB

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