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.

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