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.

1281 lines
33KB

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