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.

2903 lines
87KB

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