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.

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