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.

2909 lines
83KB

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