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.

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