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.

2590 lines
72KB

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