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.

2997 lines
86KB

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