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.

1459 lines
38KB

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