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.

1247 lines
32KB

  1. /*
  2. * Various utilities for ffmpeg system
  3. * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  4. *
  5. * This library is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU Lesser General Public
  7. * License as published by the Free Software Foundation; either
  8. * version 2 of the License, or (at your option) any later version.
  9. *
  10. * This library is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. * Lesser General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Lesser General Public
  16. * License along with this library; if not, write to the Free Software
  17. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  18. */
  19. #include "avformat.h"
  20. #include <ctype.h>
  21. #ifndef CONFIG_WIN32
  22. #include <unistd.h>
  23. #include <fcntl.h>
  24. #include <sys/time.h>
  25. #else
  26. #define strcasecmp _stricmp
  27. #include <sys/types.h>
  28. #include <sys/timeb.h>
  29. #endif
  30. #include <time.h>
  31. #ifndef HAVE_STRPTIME
  32. #include "strptime.h"
  33. #endif
  34. AVInputFormat *first_iformat;
  35. AVOutputFormat *first_oformat;
  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. ext = strrchr(filename, '.');
  57. if (ext) {
  58. ext++;
  59. p = extensions;
  60. for(;;) {
  61. q = ext1;
  62. while (*p != '\0' && *p != ',')
  63. *q++ = *p++;
  64. *q = '\0';
  65. if (!strcasecmp(ext1, ext))
  66. return 1;
  67. if (*p == '\0')
  68. break;
  69. p++;
  70. }
  71. }
  72. return 0;
  73. }
  74. AVOutputFormat *guess_format(const char *short_name, const char *filename,
  75. const char *mime_type)
  76. {
  77. AVOutputFormat *fmt, *fmt_found;
  78. int score_max, score;
  79. /* find the proper file type */
  80. fmt_found = NULL;
  81. score_max = 0;
  82. fmt = first_oformat;
  83. while (fmt != NULL) {
  84. score = 0;
  85. if (fmt->name && short_name && !strcmp(fmt->name, short_name))
  86. score += 100;
  87. if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
  88. score += 10;
  89. if (filename && fmt->extensions &&
  90. match_ext(filename, fmt->extensions)) {
  91. score += 5;
  92. }
  93. if (score > score_max) {
  94. score_max = score;
  95. fmt_found = fmt;
  96. }
  97. fmt = fmt->next;
  98. }
  99. return fmt_found;
  100. }
  101. AVOutputFormat *guess_stream_format(const char *short_name, const char *filename,
  102. const char *mime_type)
  103. {
  104. AVOutputFormat *fmt = guess_format(short_name, filename, mime_type);
  105. if (fmt) {
  106. AVOutputFormat *stream_fmt;
  107. char stream_format_name[64];
  108. snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
  109. stream_fmt = guess_format(stream_format_name, NULL, NULL);
  110. if (stream_fmt)
  111. fmt = stream_fmt;
  112. }
  113. return fmt;
  114. }
  115. AVInputFormat *av_find_input_format(const char *short_name)
  116. {
  117. AVInputFormat *fmt;
  118. for(fmt = first_iformat; fmt != NULL; fmt = fmt->next) {
  119. if (!strcmp(fmt->name, short_name))
  120. return fmt;
  121. }
  122. return NULL;
  123. }
  124. /* memory handling */
  125. /**
  126. * Allocate the payload of a packet and intialized its fields to default values.
  127. *
  128. * @param pkt packet
  129. * @param size wanted payload size
  130. * @return 0 if OK. AVERROR_xxx otherwise.
  131. */
  132. int av_new_packet(AVPacket *pkt, int size)
  133. {
  134. pkt->data = av_malloc(size);
  135. if (!pkt->data)
  136. return AVERROR_NOMEM;
  137. pkt->size = size;
  138. /* sane state */
  139. pkt->pts = AV_NOPTS_VALUE;
  140. pkt->stream_index = 0;
  141. pkt->flags = 0;
  142. return 0;
  143. }
  144. /**
  145. * Free a packet
  146. *
  147. * @param pkt packet to free
  148. */
  149. void av_free_packet(AVPacket *pkt)
  150. {
  151. av_freep(&pkt->data);
  152. /* fail safe */
  153. pkt->size = 0;
  154. }
  155. /* fifo handling */
  156. int fifo_init(FifoBuffer *f, int size)
  157. {
  158. f->buffer = av_malloc(size);
  159. if (!f->buffer)
  160. return -1;
  161. f->end = f->buffer + size;
  162. f->wptr = f->rptr = f->buffer;
  163. return 0;
  164. }
  165. void fifo_free(FifoBuffer *f)
  166. {
  167. av_free(f->buffer);
  168. }
  169. int fifo_size(FifoBuffer *f, UINT8 *rptr)
  170. {
  171. int size;
  172. if (f->wptr >= rptr) {
  173. size = f->wptr - rptr;
  174. } else {
  175. size = (f->end - rptr) + (f->wptr - f->buffer);
  176. }
  177. return size;
  178. }
  179. /* get data from the fifo (return -1 if not enough data) */
  180. int fifo_read(FifoBuffer *f, UINT8 *buf, int buf_size, UINT8 **rptr_ptr)
  181. {
  182. UINT8 *rptr = *rptr_ptr;
  183. int size, len;
  184. if (f->wptr >= rptr) {
  185. size = f->wptr - rptr;
  186. } else {
  187. size = (f->end - rptr) + (f->wptr - f->buffer);
  188. }
  189. if (size < buf_size)
  190. return -1;
  191. while (buf_size > 0) {
  192. len = f->end - rptr;
  193. if (len > buf_size)
  194. len = buf_size;
  195. memcpy(buf, rptr, len);
  196. buf += len;
  197. rptr += len;
  198. if (rptr >= f->end)
  199. rptr = f->buffer;
  200. buf_size -= len;
  201. }
  202. *rptr_ptr = rptr;
  203. return 0;
  204. }
  205. void fifo_write(FifoBuffer *f, UINT8 *buf, int size, UINT8 **wptr_ptr)
  206. {
  207. int len;
  208. UINT8 *wptr;
  209. wptr = *wptr_ptr;
  210. while (size > 0) {
  211. len = f->end - wptr;
  212. if (len > size)
  213. len = size;
  214. memcpy(wptr, buf, len);
  215. wptr += len;
  216. if (wptr >= f->end)
  217. wptr = f->buffer;
  218. buf += len;
  219. size -= len;
  220. }
  221. *wptr_ptr = wptr;
  222. }
  223. int filename_number_test(const char *filename)
  224. {
  225. char buf[1024];
  226. return get_frame_filename(buf, sizeof(buf), filename, 1);
  227. }
  228. /* guess file format */
  229. AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened)
  230. {
  231. AVInputFormat *fmt1, *fmt;
  232. int score, score_max;
  233. fmt = NULL;
  234. score_max = 0;
  235. for(fmt1 = first_iformat; fmt1 != NULL; fmt1 = fmt1->next) {
  236. if (!is_opened && !(fmt1->flags & AVFMT_NOFILE))
  237. continue;
  238. score = 0;
  239. if (fmt1->read_probe) {
  240. score = fmt1->read_probe(pd);
  241. } else if (fmt1->extensions) {
  242. if (match_ext(pd->filename, fmt1->extensions)) {
  243. score = 50;
  244. }
  245. }
  246. if (score > score_max) {
  247. score_max = score;
  248. fmt = fmt1;
  249. }
  250. }
  251. return fmt;
  252. }
  253. /************************************************************/
  254. /* input media file */
  255. #define PROBE_BUF_SIZE 2048
  256. /**
  257. * Open a media file as input. The codec are not opened. Only the file
  258. * header (if present) is read.
  259. *
  260. * @param ic_ptr the opened media file handle is put here
  261. * @param filename filename to open.
  262. * @param fmt if non NULL, force the file format to use
  263. * @param buf_size optional buffer size (zero if default is OK)
  264. * @param ap additionnal parameters needed when opening the file (NULL if default)
  265. * @return 0 if OK. AVERROR_xxx otherwise.
  266. */
  267. int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
  268. AVInputFormat *fmt,
  269. int buf_size,
  270. AVFormatParameters *ap)
  271. {
  272. AVFormatContext *ic = NULL;
  273. int err;
  274. char buf[PROBE_BUF_SIZE];
  275. AVProbeData probe_data, *pd = &probe_data;
  276. ic = av_mallocz(sizeof(AVFormatContext));
  277. if (!ic) {
  278. err = AVERROR_NOMEM;
  279. goto fail;
  280. }
  281. pstrcpy(ic->filename, sizeof(ic->filename), filename);
  282. pd->filename = ic->filename;
  283. pd->buf = buf;
  284. pd->buf_size = 0;
  285. if (!fmt) {
  286. /* guess format if no file can be opened */
  287. fmt = av_probe_input_format(pd, 0);
  288. }
  289. /* if no file needed do not try to open one */
  290. if (!fmt || !(fmt->flags & AVFMT_NOFILE)) {
  291. if (url_fopen(&ic->pb, filename, URL_RDONLY) < 0) {
  292. err = AVERROR_IO;
  293. goto fail;
  294. }
  295. if (buf_size > 0) {
  296. url_setbufsize(&ic->pb, buf_size);
  297. }
  298. /* read probe data */
  299. pd->buf_size = get_buffer(&ic->pb, buf, PROBE_BUF_SIZE);
  300. url_fseek(&ic->pb, 0, SEEK_SET);
  301. }
  302. /* guess file format */
  303. if (!fmt) {
  304. fmt = av_probe_input_format(pd, 1);
  305. }
  306. /* if still no format found, error */
  307. if (!fmt) {
  308. err = AVERROR_NOFMT;
  309. goto fail;
  310. }
  311. ic->iformat = fmt;
  312. /* allocate private data */
  313. ic->priv_data = av_mallocz(fmt->priv_data_size);
  314. if (!ic->priv_data) {
  315. err = AVERROR_NOMEM;
  316. goto fail;
  317. }
  318. /* default pts settings is MPEG like */
  319. av_set_pts_info(ic, 33, 1, 90000);
  320. /* check filename in case of an image number is expected */
  321. if (ic->iformat->flags & AVFMT_NEEDNUMBER) {
  322. if (filename_number_test(ic->filename) < 0) {
  323. err = AVERROR_NUMEXPECTED;
  324. goto fail1;
  325. }
  326. }
  327. err = ic->iformat->read_header(ic, ap);
  328. if (err < 0)
  329. goto fail1;
  330. *ic_ptr = ic;
  331. return 0;
  332. fail1:
  333. if (!(fmt->flags & AVFMT_NOFILE)) {
  334. url_fclose(&ic->pb);
  335. }
  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. /**
  345. * Read a packet from a media file
  346. * @param s media file handle
  347. * @param pkt is filled
  348. * @return 0 if OK. AVERROR_xxx if error.
  349. */
  350. int av_read_packet(AVFormatContext *s, AVPacket *pkt)
  351. {
  352. AVPacketList *pktl;
  353. pktl = s->packet_buffer;
  354. if (pktl) {
  355. /* read packet from packet buffer, if there is data */
  356. *pkt = pktl->pkt;
  357. s->packet_buffer = pktl->next;
  358. av_free(pktl);
  359. return 0;
  360. } else {
  361. return s->iformat->read_packet(s, pkt);
  362. }
  363. }
  364. /* state for codec information */
  365. #define CSTATE_NOTFOUND 0
  366. #define CSTATE_DECODING 1
  367. #define CSTATE_FOUND 2
  368. static int has_codec_parameters(AVCodecContext *enc)
  369. {
  370. int val;
  371. switch(enc->codec_type) {
  372. case CODEC_TYPE_AUDIO:
  373. val = enc->sample_rate;
  374. break;
  375. case CODEC_TYPE_VIDEO:
  376. val = enc->width;
  377. break;
  378. default:
  379. val = 1;
  380. break;
  381. }
  382. return (val != 0);
  383. }
  384. /**
  385. * Read the beginning of a media file to get stream information. This
  386. * is useful for file formats with no headers such as MPEG. This
  387. * function also compute the real frame rate in case of mpeg2 repeat
  388. * frame mode.
  389. *
  390. * @param ic media file handle
  391. * @return >=0 if OK. AVERROR_xxx if error.
  392. */
  393. int av_find_stream_info(AVFormatContext *ic)
  394. {
  395. int i, count, ret, got_picture, size, read_size;
  396. AVCodec *codec;
  397. AVStream *st;
  398. AVPacket *pkt;
  399. AVPicture picture;
  400. AVPacketList *pktl=NULL, **ppktl;
  401. short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
  402. UINT8 *ptr;
  403. int min_read_size, max_read_size;
  404. /* typical mpeg ts rate is 40 Mbits. DVD rate is about 10
  405. Mbits. We read at most 0.1 second of file to find all streams */
  406. /* XXX: base it on stream bitrate when possible */
  407. if (ic->iformat == &mpegts_demux) {
  408. /* maximum number of bytes we accept to read to find all the streams
  409. in a file */
  410. min_read_size = 3000000;
  411. } else {
  412. min_read_size = 125000;
  413. }
  414. /* max read size is 2 seconds of video max */
  415. max_read_size = min_read_size * 20;
  416. /* set initial codec state */
  417. for(i=0;i<ic->nb_streams;i++) {
  418. st = ic->streams[i];
  419. if (has_codec_parameters(&st->codec))
  420. st->codec_info_state = CSTATE_FOUND;
  421. else
  422. st->codec_info_state = CSTATE_NOTFOUND;
  423. st->codec_info_nb_repeat_frames = 0;
  424. st->codec_info_nb_real_frames = 0;
  425. }
  426. count = 0;
  427. read_size = 0;
  428. ppktl = &ic->packet_buffer;
  429. for(;;) {
  430. /* check if one codec still needs to be handled */
  431. for(i=0;i<ic->nb_streams;i++) {
  432. st = ic->streams[i];
  433. if (st->codec_info_state != CSTATE_FOUND)
  434. break;
  435. }
  436. if (i == ic->nb_streams) {
  437. /* NOTE: if the format has no header, then we need to read
  438. some packets to get most of the streams, so we cannot
  439. stop here */
  440. if (!(ic->iformat->flags & AVFMT_NOHEADER) ||
  441. read_size >= min_read_size) {
  442. /* if we found the info for all the codecs, we can stop */
  443. ret = count;
  444. break;
  445. }
  446. } else {
  447. /* we did not get all the codec info, but we read too much data */
  448. if (read_size >= max_read_size) {
  449. ret = count;
  450. break;
  451. }
  452. }
  453. pktl = av_mallocz(sizeof(AVPacketList));
  454. if (!pktl) {
  455. ret = AVERROR_NOMEM;
  456. break;
  457. }
  458. /* add the packet in the buffered packet list */
  459. *ppktl = pktl;
  460. ppktl = &pktl->next;
  461. /* NOTE: a new stream can be added there if no header in file
  462. (AVFMT_NOHEADER) */
  463. pkt = &pktl->pkt;
  464. if (ic->iformat->read_packet(ic, pkt) < 0) {
  465. /* EOF or error */
  466. ret = -1; /* we could not have all the codec parameters before EOF */
  467. if ((ic->iformat->flags & AVFMT_NOHEADER) &&
  468. i == ic->nb_streams)
  469. ret = 0;
  470. break;
  471. }
  472. read_size += pkt->size;
  473. /* open new codecs */
  474. for(i=0;i<ic->nb_streams;i++) {
  475. st = ic->streams[i];
  476. if (st->codec_info_state == CSTATE_NOTFOUND) {
  477. /* set to found in case of error */
  478. st->codec_info_state = CSTATE_FOUND;
  479. codec = avcodec_find_decoder(st->codec.codec_id);
  480. if (codec) {
  481. ret = avcodec_open(&st->codec, codec);
  482. if (ret >= 0)
  483. st->codec_info_state = CSTATE_DECODING;
  484. }
  485. }
  486. }
  487. st = ic->streams[pkt->stream_index];
  488. if (st->codec_info_state == CSTATE_DECODING) {
  489. /* decode the data and update codec parameters */
  490. ptr = pkt->data;
  491. size = pkt->size;
  492. while (size > 0) {
  493. switch(st->codec.codec_type) {
  494. case CODEC_TYPE_VIDEO:
  495. ret = avcodec_decode_video(&st->codec, &picture,
  496. &got_picture, ptr, size);
  497. break;
  498. case CODEC_TYPE_AUDIO:
  499. ret = avcodec_decode_audio(&st->codec, samples,
  500. &got_picture, ptr, size);
  501. break;
  502. default:
  503. ret = -1;
  504. break;
  505. }
  506. if (ret < 0) {
  507. /* if error, simply ignore because another packet
  508. may be OK */
  509. break;
  510. }
  511. if (got_picture) {
  512. /* we got the parameters - now we can stop
  513. examining this stream */
  514. /* XXX: add a codec info so that we can decide if
  515. the codec can repeat frames */
  516. if (st->codec.codec_id == CODEC_ID_MPEG1VIDEO &&
  517. ic->iformat != &mpegts_demux &&
  518. st->codec.sub_id == 2) {
  519. /* for mpeg2 video, we want to know the real
  520. frame rate, so we decode 40 frames. In mpeg
  521. TS case we do not do it because it would be
  522. too long */
  523. st->codec_info_nb_real_frames++;
  524. st->codec_info_nb_repeat_frames += st->codec.repeat_pict;
  525. #if 0
  526. /* XXX: testing */
  527. if ((st->codec_info_nb_real_frames % 24) == 23) {
  528. st->codec_info_nb_repeat_frames += 2;
  529. }
  530. #endif
  531. /* stop after 40 frames */
  532. if (st->codec_info_nb_real_frames >= 40) {
  533. st->r_frame_rate = (st->codec.frame_rate *
  534. st->codec_info_nb_real_frames) /
  535. (st->codec_info_nb_real_frames +
  536. (st->codec_info_nb_repeat_frames >> 1));
  537. goto close_codec;
  538. }
  539. } else {
  540. close_codec:
  541. st->codec_info_state = CSTATE_FOUND;
  542. avcodec_close(&st->codec);
  543. break;
  544. }
  545. }
  546. ptr += ret;
  547. size -= ret;
  548. }
  549. }
  550. count++;
  551. }
  552. /* close each codec if there are opened */
  553. for(i=0;i<ic->nb_streams;i++) {
  554. st = ic->streams[i];
  555. if (st->codec_info_state == CSTATE_DECODING)
  556. avcodec_close(&st->codec);
  557. }
  558. /* set real frame rate info */
  559. for(i=0;i<ic->nb_streams;i++) {
  560. st = ic->streams[i];
  561. if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
  562. if (!st->r_frame_rate)
  563. st->r_frame_rate = st->codec.frame_rate;
  564. }
  565. }
  566. return ret;
  567. }
  568. /**
  569. * Close a media file (but not its codecs)
  570. *
  571. * @param s media file handle
  572. */
  573. void av_close_input_file(AVFormatContext *s)
  574. {
  575. int i;
  576. if (s->iformat->read_close)
  577. s->iformat->read_close(s);
  578. for(i=0;i<s->nb_streams;i++) {
  579. av_free(s->streams[i]);
  580. }
  581. if (s->packet_buffer) {
  582. AVPacketList *p, *p1;
  583. p = s->packet_buffer;
  584. while (p != NULL) {
  585. p1 = p->next;
  586. av_free_packet(&p->pkt);
  587. av_free(p);
  588. p = p1;
  589. }
  590. s->packet_buffer = NULL;
  591. }
  592. if (!(s->iformat->flags & AVFMT_NOFILE)) {
  593. url_fclose(&s->pb);
  594. }
  595. av_freep(&s->priv_data);
  596. av_free(s);
  597. }
  598. /**
  599. * Add a new stream to a media file. Can only be called in the
  600. * read_header function. If the flag AVFMT_NOHEADER is in the format
  601. * description, then new streams can be added in read_packet too.
  602. *
  603. *
  604. * @param s media file handle
  605. * @param id file format dependent stream id
  606. */
  607. AVStream *av_new_stream(AVFormatContext *s, int id)
  608. {
  609. AVStream *st;
  610. if (s->nb_streams >= MAX_STREAMS)
  611. return NULL;
  612. st = av_mallocz(sizeof(AVStream));
  613. if (!st)
  614. return NULL;
  615. st->index = s->nb_streams;
  616. st->id = id;
  617. s->streams[s->nb_streams++] = st;
  618. return st;
  619. }
  620. /************************************************************/
  621. /* output media file */
  622. /**
  623. * allocate the stream private data and write the stream header to an
  624. * output media file
  625. *
  626. * @param s media file handle
  627. * @return 0 if OK. AVERROR_xxx if error.
  628. */
  629. int av_write_header(AVFormatContext *s)
  630. {
  631. int ret, i;
  632. AVStream *st;
  633. s->priv_data = av_mallocz(s->oformat->priv_data_size);
  634. if (!s->priv_data)
  635. return AVERROR_NOMEM;
  636. /* default pts settings is MPEG like */
  637. av_set_pts_info(s, 33, 1, 90000);
  638. ret = s->oformat->write_header(s);
  639. if (ret < 0)
  640. return ret;
  641. /* init PTS generation */
  642. for(i=0;i<s->nb_streams;i++) {
  643. st = s->streams[i];
  644. switch (st->codec.codec_type) {
  645. case CODEC_TYPE_AUDIO:
  646. av_frac_init(&st->pts, 0, 0,
  647. (INT64)s->pts_num * st->codec.sample_rate);
  648. break;
  649. case CODEC_TYPE_VIDEO:
  650. av_frac_init(&st->pts, 0, 0,
  651. (INT64)s->pts_num * st->codec.frame_rate);
  652. break;
  653. default:
  654. break;
  655. }
  656. }
  657. return 0;
  658. }
  659. /**
  660. * Write a packet to an output media file. The packet shall contain
  661. * one audio or video frame.
  662. *
  663. * @param s media file handle
  664. * @param stream_index stream index
  665. * @param buf buffer containing the frame data
  666. * @param size size of buffer
  667. * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
  668. */
  669. int av_write_frame(AVFormatContext *s, int stream_index, const uint8_t *buf,
  670. int size)
  671. {
  672. AVStream *st;
  673. INT64 pts_mask;
  674. int ret;
  675. st = s->streams[stream_index];
  676. pts_mask = (1LL << s->pts_wrap_bits) - 1;
  677. ret = s->oformat->write_packet(s, stream_index, (uint8_t *)buf, size,
  678. st->pts.val & pts_mask);
  679. if (ret < 0)
  680. return ret;
  681. /* update pts */
  682. switch (st->codec.codec_type) {
  683. case CODEC_TYPE_AUDIO:
  684. av_frac_add(&st->pts,
  685. (INT64)s->pts_den * st->codec.frame_size);
  686. break;
  687. case CODEC_TYPE_VIDEO:
  688. av_frac_add(&st->pts,
  689. (INT64)s->pts_den * FRAME_RATE_BASE);
  690. break;
  691. default:
  692. break;
  693. }
  694. return ret;
  695. }
  696. /**
  697. * write the stream trailer to an output media file and and free the
  698. * file private data.
  699. *
  700. * @param s media file handle
  701. * @return 0 if OK. AVERROR_xxx if error. */
  702. int av_write_trailer(AVFormatContext *s)
  703. {
  704. int ret;
  705. ret = s->oformat->write_trailer(s);
  706. av_freep(&s->priv_data);
  707. return ret;
  708. }
  709. /* "user interface" functions */
  710. void dump_format(AVFormatContext *ic,
  711. int index,
  712. const char *url,
  713. int is_output)
  714. {
  715. int i, flags;
  716. char buf[256];
  717. fprintf(stderr, "%s #%d, %s, %s '%s':\n",
  718. is_output ? "Output" : "Input",
  719. index,
  720. is_output ? ic->oformat->name : ic->iformat->name,
  721. is_output ? "to" : "from", url);
  722. for(i=0;i<ic->nb_streams;i++) {
  723. AVStream *st = ic->streams[i];
  724. avcodec_string(buf, sizeof(buf), &st->codec, is_output);
  725. fprintf(stderr, " Stream #%d.%d", index, i);
  726. /* the pid is an important information, so we display it */
  727. /* XXX: add a generic system */
  728. if (is_output)
  729. flags = ic->oformat->flags;
  730. else
  731. flags = ic->iformat->flags;
  732. if (flags & AVFMT_SHOW_IDS) {
  733. fprintf(stderr, "[0x%x]", st->id);
  734. }
  735. fprintf(stderr, ": %s\n", buf);
  736. }
  737. }
  738. typedef struct {
  739. const char *str;
  740. int width, height;
  741. } SizeEntry;
  742. static SizeEntry sizes[] = {
  743. { "sqcif", 128, 96 },
  744. { "qcif", 176, 144 },
  745. { "cif", 352, 288 },
  746. { "4cif", 704, 576 },
  747. };
  748. int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
  749. {
  750. int i;
  751. int n = sizeof(sizes) / sizeof(SizeEntry);
  752. const char *p;
  753. int frame_width = 0, frame_height = 0;
  754. for(i=0;i<n;i++) {
  755. if (!strcmp(sizes[i].str, str)) {
  756. frame_width = sizes[i].width;
  757. frame_height = sizes[i].height;
  758. break;
  759. }
  760. }
  761. if (i == n) {
  762. p = str;
  763. frame_width = strtol(p, (char **)&p, 10);
  764. if (*p)
  765. p++;
  766. frame_height = strtol(p, (char **)&p, 10);
  767. }
  768. if (frame_width <= 0 || frame_height <= 0)
  769. return -1;
  770. *width_ptr = frame_width;
  771. *height_ptr = frame_height;
  772. return 0;
  773. }
  774. INT64 av_gettime(void)
  775. {
  776. #ifdef CONFIG_WIN32
  777. struct _timeb tb;
  778. _ftime(&tb);
  779. return ((INT64)tb.time * INT64_C(1000) + (INT64)tb.millitm) * INT64_C(1000);
  780. #else
  781. struct timeval tv;
  782. gettimeofday(&tv,NULL);
  783. return (INT64)tv.tv_sec * 1000000 + tv.tv_usec;
  784. #endif
  785. }
  786. static time_t mktimegm(struct tm *tm)
  787. {
  788. time_t t;
  789. int y = tm->tm_year + 1900, m = tm->tm_mon + 1, d = tm->tm_mday;
  790. if (m < 3) {
  791. m += 12;
  792. y--;
  793. }
  794. t = 86400 *
  795. (d + (153 * m - 457) / 5 + 365 * y + y / 4 - y / 100 + y / 400 - 719469);
  796. t += 3600 * tm->tm_hour + 60 * tm->tm_min + tm->tm_sec;
  797. return t;
  798. }
  799. /* Syntax:
  800. * - If not a duration:
  801. * [{YYYY-MM-DD|YYYYMMDD}]{T| }{HH[:MM[:SS[.m...]]][Z]|HH[MM[SS[.m...]]][Z]}
  802. * Time is localtime unless Z is suffixed to the end. In this case GMT
  803. * Return the date in micro seconds since 1970
  804. * - If duration:
  805. * HH[:MM[:SS[.m...]]]
  806. * S+[.m...]
  807. */
  808. INT64 parse_date(const char *datestr, int duration)
  809. {
  810. const char *p;
  811. INT64 t;
  812. struct tm dt;
  813. int i;
  814. static const char *date_fmt[] = {
  815. "%Y-%m-%d",
  816. "%Y%m%d",
  817. };
  818. static const char *time_fmt[] = {
  819. "%H:%M:%S",
  820. "%H%M%S",
  821. };
  822. const char *q;
  823. int is_utc, len;
  824. char lastch;
  825. time_t now = time(0);
  826. len = strlen(datestr);
  827. if (len > 0)
  828. lastch = datestr[len - 1];
  829. else
  830. lastch = '\0';
  831. is_utc = (lastch == 'z' || lastch == 'Z');
  832. memset(&dt, 0, sizeof(dt));
  833. p = datestr;
  834. q = NULL;
  835. if (!duration) {
  836. for (i = 0; i < sizeof(date_fmt) / sizeof(date_fmt[0]); i++) {
  837. q = strptime(p, date_fmt[i], &dt);
  838. if (q) {
  839. break;
  840. }
  841. }
  842. if (!q) {
  843. if (is_utc) {
  844. dt = *gmtime(&now);
  845. } else {
  846. dt = *localtime(&now);
  847. }
  848. dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
  849. } else {
  850. p = q;
  851. }
  852. if (*p == 'T' || *p == 't' || *p == ' ')
  853. p++;
  854. for (i = 0; i < sizeof(time_fmt) / sizeof(time_fmt[0]); i++) {
  855. q = strptime(p, time_fmt[i], &dt);
  856. if (q) {
  857. break;
  858. }
  859. }
  860. } else {
  861. q = strptime(p, time_fmt[0], &dt);
  862. if (!q) {
  863. dt.tm_sec = strtol(p, (char **)&q, 10);
  864. dt.tm_min = 0;
  865. dt.tm_hour = 0;
  866. }
  867. }
  868. /* Now we have all the fields that we can get */
  869. if (!q) {
  870. if (duration)
  871. return 0;
  872. else
  873. return now * INT64_C(1000000);
  874. }
  875. if (duration) {
  876. t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
  877. } else {
  878. dt.tm_isdst = -1; /* unknown */
  879. if (is_utc) {
  880. t = mktimegm(&dt);
  881. } else {
  882. t = mktime(&dt);
  883. }
  884. }
  885. t *= 1000000;
  886. if (*q == '.') {
  887. int val, n;
  888. q++;
  889. for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
  890. if (!isdigit(*q))
  891. break;
  892. val += n * (*q - '0');
  893. }
  894. t += val;
  895. }
  896. return t;
  897. }
  898. /* syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done. Return
  899. 1 if found */
  900. int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
  901. {
  902. const char *p;
  903. char tag[128], *q;
  904. p = info;
  905. if (*p == '?')
  906. p++;
  907. for(;;) {
  908. q = tag;
  909. while (*p != '\0' && *p != '=' && *p != '&') {
  910. if ((q - tag) < sizeof(tag) - 1)
  911. *q++ = *p;
  912. p++;
  913. }
  914. *q = '\0';
  915. q = arg;
  916. if (*p == '=') {
  917. p++;
  918. while (*p != '&' && *p != '\0') {
  919. if ((q - arg) < arg_size - 1) {
  920. if (*p == '+')
  921. *q++ = ' ';
  922. else
  923. *q++ = *p;
  924. }
  925. p++;
  926. }
  927. *q = '\0';
  928. }
  929. if (!strcmp(tag, tag1))
  930. return 1;
  931. if (*p != '&')
  932. break;
  933. p++;
  934. }
  935. return 0;
  936. }
  937. /* Return in 'buf' the path with '%d' replaced by number. Also handles
  938. the '%0nd' format where 'n' is the total number of digits and
  939. '%%'. Return 0 if OK, and -1 if format error */
  940. int get_frame_filename(char *buf, int buf_size,
  941. const char *path, int number)
  942. {
  943. const char *p;
  944. char *q, buf1[20];
  945. int nd, len, c, percentd_found;
  946. q = buf;
  947. p = path;
  948. percentd_found = 0;
  949. for(;;) {
  950. c = *p++;
  951. if (c == '\0')
  952. break;
  953. if (c == '%') {
  954. nd = 0;
  955. while (*p >= '0' && *p <= '9') {
  956. nd = nd * 10 + *p++ - '0';
  957. }
  958. c = *p++;
  959. switch(c) {
  960. case '%':
  961. goto addchar;
  962. case 'd':
  963. if (percentd_found)
  964. goto fail;
  965. percentd_found = 1;
  966. snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
  967. len = strlen(buf1);
  968. if ((q - buf + len) > buf_size - 1)
  969. goto fail;
  970. memcpy(q, buf1, len);
  971. q += len;
  972. break;
  973. default:
  974. goto fail;
  975. }
  976. } else {
  977. addchar:
  978. if ((q - buf) < buf_size - 1)
  979. *q++ = c;
  980. }
  981. }
  982. if (!percentd_found)
  983. goto fail;
  984. *q = '\0';
  985. return 0;
  986. fail:
  987. *q = '\0';
  988. return -1;
  989. }
  990. /**
  991. *
  992. * Print on stdout a nice hexa dump of a buffer
  993. * @param buf buffer
  994. * @param size buffer size
  995. */
  996. void av_hex_dump(UINT8 *buf, int size)
  997. {
  998. int len, i, j, c;
  999. for(i=0;i<size;i+=16) {
  1000. len = size - i;
  1001. if (len > 16)
  1002. len = 16;
  1003. printf("%08x ", i);
  1004. for(j=0;j<16;j++) {
  1005. if (j < len)
  1006. printf(" %02x", buf[i+j]);
  1007. else
  1008. printf(" ");
  1009. }
  1010. printf(" ");
  1011. for(j=0;j<len;j++) {
  1012. c = buf[i+j];
  1013. if (c < ' ' || c > '~')
  1014. c = '.';
  1015. printf("%c", c);
  1016. }
  1017. printf("\n");
  1018. }
  1019. }
  1020. void url_split(char *proto, int proto_size,
  1021. char *hostname, int hostname_size,
  1022. int *port_ptr,
  1023. char *path, int path_size,
  1024. const char *url)
  1025. {
  1026. const char *p;
  1027. char *q;
  1028. int port;
  1029. port = -1;
  1030. p = url;
  1031. q = proto;
  1032. while (*p != ':' && *p != '\0') {
  1033. if ((q - proto) < proto_size - 1)
  1034. *q++ = *p;
  1035. p++;
  1036. }
  1037. if (proto_size > 0)
  1038. *q = '\0';
  1039. if (*p == '\0') {
  1040. if (proto_size > 0)
  1041. proto[0] = '\0';
  1042. if (hostname_size > 0)
  1043. hostname[0] = '\0';
  1044. p = url;
  1045. } else {
  1046. p++;
  1047. if (*p == '/')
  1048. p++;
  1049. if (*p == '/')
  1050. p++;
  1051. q = hostname;
  1052. while (*p != ':' && *p != '/' && *p != '?' && *p != '\0') {
  1053. if ((q - hostname) < hostname_size - 1)
  1054. *q++ = *p;
  1055. p++;
  1056. }
  1057. if (hostname_size > 0)
  1058. *q = '\0';
  1059. if (*p == ':') {
  1060. p++;
  1061. port = strtoul(p, (char **)&p, 10);
  1062. }
  1063. }
  1064. if (port_ptr)
  1065. *port_ptr = port;
  1066. pstrcpy(path, path_size, p);
  1067. }
  1068. /**
  1069. * Set the pts for a given stream
  1070. * @param s stream
  1071. * @param pts_wrap_bits number of bits effectively used by the pts
  1072. * (used for wrap control, 33 is the value for MPEG)
  1073. * @param pts_num numerator to convert to seconds (MPEG: 1)
  1074. * @param pts_den denominator to convert to seconds (MPEG: 90000)
  1075. */
  1076. void av_set_pts_info(AVFormatContext *s, int pts_wrap_bits,
  1077. int pts_num, int pts_den)
  1078. {
  1079. s->pts_wrap_bits = pts_wrap_bits;
  1080. s->pts_num = pts_num;
  1081. s->pts_den = pts_den;
  1082. }
  1083. /* fraction handling */
  1084. /**
  1085. * f = val + (num / den) + 0.5. 'num' is normalized so that it is such
  1086. * as 0 <= num < den.
  1087. *
  1088. * @param f fractional number
  1089. * @param val integer value
  1090. * @param num must be >= 0
  1091. * @param den must be >= 1
  1092. */
  1093. void av_frac_init(AVFrac *f, INT64 val, INT64 num, INT64 den)
  1094. {
  1095. num += (den >> 1);
  1096. if (num >= den) {
  1097. val += num / den;
  1098. num = num % den;
  1099. }
  1100. f->val = val;
  1101. f->num = num;
  1102. f->den = den;
  1103. }
  1104. /* set f to (val + 0.5) */
  1105. void av_frac_set(AVFrac *f, INT64 val)
  1106. {
  1107. f->val = val;
  1108. f->num = f->den >> 1;
  1109. }
  1110. /**
  1111. * Fractionnal addition to f: f = f + (incr / f->den)
  1112. *
  1113. * @param f fractional number
  1114. * @param incr increment, can be positive or negative
  1115. */
  1116. void av_frac_add(AVFrac *f, INT64 incr)
  1117. {
  1118. INT64 num, den;
  1119. num = f->num + incr;
  1120. den = f->den;
  1121. if (num < 0) {
  1122. f->val += num / den;
  1123. num = num % den;
  1124. if (num < 0) {
  1125. num += den;
  1126. f->val--;
  1127. }
  1128. } else if (num >= den) {
  1129. f->val += num / den;
  1130. num = num % den;
  1131. }
  1132. f->num = num;
  1133. }