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.

3120 lines
93KB

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