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.

1403 lines
35KB

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