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.

3308 lines
95KB

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