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.

3284 lines
94KB

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