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.

3290 lines
95KB

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