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.

3312 lines
96KB

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