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.

3327 lines
96KB

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