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.

1786 lines
47KB

  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. ic->duration = AV_NOPTS_VALUE;
  290. ic->start_time = AV_NOPTS_VALUE;
  291. pstrcpy(ic->filename, sizeof(ic->filename), filename);
  292. pd->filename = ic->filename;
  293. pd->buf = buf;
  294. pd->buf_size = 0;
  295. if (!fmt) {
  296. /* guess format if no file can be opened */
  297. fmt = av_probe_input_format(pd, 0);
  298. }
  299. /* do not open file if the format does not need it. XXX: specific
  300. hack needed to handle RTSP/TCP */
  301. must_open_file = 1;
  302. if ((fmt && (fmt->flags & AVFMT_NOFILE))
  303. #ifdef CONFIG_NETWORK
  304. || (fmt == &rtp_demux && !strcmp(filename, "null"))
  305. #endif
  306. ) {
  307. must_open_file = 0;
  308. }
  309. if (!fmt || must_open_file) {
  310. /* if no file needed do not try to open one */
  311. if (url_fopen(&ic->pb, filename, URL_RDONLY) < 0) {
  312. err = AVERROR_IO;
  313. goto fail;
  314. }
  315. if (buf_size > 0) {
  316. url_setbufsize(&ic->pb, buf_size);
  317. }
  318. if (!fmt) {
  319. /* read probe data */
  320. pd->buf_size = get_buffer(&ic->pb, buf, PROBE_BUF_SIZE);
  321. url_fseek(&ic->pb, 0, SEEK_SET);
  322. }
  323. }
  324. /* guess file format */
  325. if (!fmt) {
  326. fmt = av_probe_input_format(pd, 1);
  327. }
  328. /* if still no format found, error */
  329. if (!fmt) {
  330. err = AVERROR_NOFMT;
  331. goto fail1;
  332. }
  333. /* XXX: suppress this hack for redirectors */
  334. #ifdef CONFIG_NETWORK
  335. if (fmt == &redir_demux) {
  336. err = redir_open(ic_ptr, &ic->pb);
  337. url_fclose(&ic->pb);
  338. av_free(ic);
  339. return err;
  340. }
  341. #endif
  342. ic->iformat = fmt;
  343. /* check filename in case of an image number is expected */
  344. if (ic->iformat->flags & AVFMT_NEEDNUMBER) {
  345. if (filename_number_test(ic->filename) < 0) {
  346. err = AVERROR_NUMEXPECTED;
  347. goto fail1;
  348. }
  349. }
  350. /* allocate private data */
  351. if (fmt->priv_data_size > 0) {
  352. ic->priv_data = av_mallocz(fmt->priv_data_size);
  353. if (!ic->priv_data) {
  354. err = AVERROR_NOMEM;
  355. goto fail1;
  356. }
  357. } else
  358. ic->priv_data = NULL;
  359. /* default pts settings is MPEG like */
  360. av_set_pts_info(ic, 33, 1, 90000);
  361. err = ic->iformat->read_header(ic, ap);
  362. if (err < 0)
  363. goto fail1;
  364. *ic_ptr = ic;
  365. return 0;
  366. fail1:
  367. if (!fmt || must_open_file) {
  368. url_fclose(&ic->pb);
  369. }
  370. fail:
  371. if (ic) {
  372. av_freep(&ic->priv_data);
  373. }
  374. av_free(ic);
  375. *ic_ptr = NULL;
  376. return err;
  377. }
  378. /**
  379. * Read a packet from a media file
  380. * @param s media file handle
  381. * @param pkt is filled
  382. * @return 0 if OK. AVERROR_xxx if error.
  383. */
  384. int av_read_packet(AVFormatContext *s, AVPacket *pkt)
  385. {
  386. AVPacketList *pktl;
  387. pktl = s->packet_buffer;
  388. if (pktl) {
  389. /* read packet from packet buffer, if there is data */
  390. *pkt = pktl->pkt;
  391. s->packet_buffer = pktl->next;
  392. av_free(pktl);
  393. return 0;
  394. } else {
  395. return s->iformat->read_packet(s, pkt);
  396. }
  397. }
  398. /* return TRUE if the stream has accurate timings for at least one component */
  399. static int av_has_timings(AVFormatContext *ic)
  400. {
  401. int i;
  402. AVStream *st;
  403. for(i = 0;i < ic->nb_streams; i++) {
  404. st = ic->streams[i];
  405. if (st->start_time != AV_NOPTS_VALUE &&
  406. st->duration != AV_NOPTS_VALUE)
  407. return 1;
  408. }
  409. return 0;
  410. }
  411. /* estimate the stream timings from the one of each components. Also
  412. compute the global bitrate if possible */
  413. static void av_update_stream_timings(AVFormatContext *ic)
  414. {
  415. int64_t start_time, end_time, end_time1;
  416. int i;
  417. AVStream *st;
  418. start_time = MAXINT64;
  419. end_time = MININT64;
  420. for(i = 0;i < ic->nb_streams; i++) {
  421. st = ic->streams[i];
  422. if (st->start_time != AV_NOPTS_VALUE) {
  423. if (st->start_time < start_time)
  424. start_time = st->start_time;
  425. if (st->duration != AV_NOPTS_VALUE) {
  426. end_time1 = st->start_time + st->duration;
  427. if (end_time1 > end_time)
  428. end_time = end_time1;
  429. }
  430. }
  431. }
  432. if (start_time != MAXINT64) {
  433. ic->start_time = start_time;
  434. if (end_time != MAXINT64) {
  435. ic->duration = end_time - start_time;
  436. if (ic->file_size > 0) {
  437. /* compute the bit rate */
  438. ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE /
  439. (double)ic->duration;
  440. }
  441. }
  442. }
  443. }
  444. static void fill_all_stream_timings(AVFormatContext *ic)
  445. {
  446. int i;
  447. AVStream *st;
  448. av_update_stream_timings(ic);
  449. for(i = 0;i < ic->nb_streams; i++) {
  450. st = ic->streams[i];
  451. if (st->start_time == AV_NOPTS_VALUE) {
  452. st->start_time = ic->start_time;
  453. st->duration = ic->duration;
  454. }
  455. }
  456. }
  457. static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
  458. {
  459. int64_t filesize, duration;
  460. int bit_rate, i;
  461. AVStream *st;
  462. /* if bit_rate is already set, we believe it */
  463. if (ic->bit_rate == 0) {
  464. bit_rate = 0;
  465. for(i=0;i<ic->nb_streams;i++) {
  466. st = ic->streams[i];
  467. bit_rate += st->codec.bit_rate;
  468. }
  469. ic->bit_rate = bit_rate;
  470. }
  471. /* if duration is already set, we believe it */
  472. if (ic->duration == AV_NOPTS_VALUE &&
  473. ic->bit_rate != 0 &&
  474. ic->file_size != 0) {
  475. filesize = ic->file_size;
  476. if (filesize > 0) {
  477. duration = (int64_t)((8 * AV_TIME_BASE * (double)filesize) / (double)ic->bit_rate);
  478. for(i = 0; i < ic->nb_streams; i++) {
  479. st = ic->streams[i];
  480. if (st->start_time == AV_NOPTS_VALUE ||
  481. st->duration == AV_NOPTS_VALUE) {
  482. st->start_time = 0;
  483. st->duration = duration;
  484. }
  485. }
  486. }
  487. }
  488. }
  489. static void flush_packet_queue(AVFormatContext *s)
  490. {
  491. AVPacketList *pktl;
  492. for(;;) {
  493. pktl = s->packet_buffer;
  494. if (!pktl)
  495. break;
  496. s->packet_buffer = pktl->next;
  497. av_free(pktl);
  498. }
  499. }
  500. #define DURATION_MAX_READ_SIZE 250000
  501. /* only usable for MPEG-PS streams */
  502. static void av_estimate_timings_from_pts(AVFormatContext *ic)
  503. {
  504. AVPacket pkt1, *pkt = &pkt1;
  505. AVStream *st;
  506. int read_size, i, ret;
  507. int64_t start_time, end_time, end_time1;
  508. int64_t filesize, offset, duration;
  509. /* we read the first packets to get the first PTS (not fully
  510. accurate, but it is enough now) */
  511. url_fseek(&ic->pb, 0, SEEK_SET);
  512. read_size = 0;
  513. for(;;) {
  514. if (read_size >= DURATION_MAX_READ_SIZE)
  515. break;
  516. /* if all info is available, we can stop */
  517. for(i = 0;i < ic->nb_streams; i++) {
  518. st = ic->streams[i];
  519. if (st->start_time == AV_NOPTS_VALUE)
  520. break;
  521. }
  522. if (i == ic->nb_streams)
  523. break;
  524. ret = av_read_packet(ic, pkt);
  525. if (ret != 0)
  526. break;
  527. read_size += pkt->size;
  528. st = ic->streams[pkt->stream_index];
  529. if (pkt->pts != AV_NOPTS_VALUE) {
  530. if (st->start_time == AV_NOPTS_VALUE)
  531. st->start_time = (int64_t)((double)pkt->pts * ic->pts_num * (double)AV_TIME_BASE / ic->pts_den);
  532. }
  533. av_free_packet(pkt);
  534. }
  535. /* we compute the minimum start_time and use it as default */
  536. start_time = MAXINT64;
  537. for(i = 0; i < ic->nb_streams; i++) {
  538. st = ic->streams[i];
  539. if (st->start_time != AV_NOPTS_VALUE &&
  540. st->start_time < start_time)
  541. start_time = st->start_time;
  542. }
  543. fprintf(stderr, "start=%lld\n", start_time);
  544. if (start_time != MAXINT64)
  545. ic->start_time = start_time;
  546. /* estimate the end time (duration) */
  547. /* XXX: may need to support wrapping */
  548. filesize = ic->file_size;
  549. offset = filesize - DURATION_MAX_READ_SIZE;
  550. if (offset < 0)
  551. offset = 0;
  552. /* flush packet queue */
  553. flush_packet_queue(ic);
  554. url_fseek(&ic->pb, offset, SEEK_SET);
  555. read_size = 0;
  556. for(;;) {
  557. if (read_size >= DURATION_MAX_READ_SIZE)
  558. break;
  559. /* if all info is available, we can stop */
  560. for(i = 0;i < ic->nb_streams; i++) {
  561. st = ic->streams[i];
  562. if (st->duration == AV_NOPTS_VALUE)
  563. break;
  564. }
  565. if (i == ic->nb_streams)
  566. break;
  567. ret = av_read_packet(ic, pkt);
  568. if (ret != 0)
  569. break;
  570. read_size += pkt->size;
  571. st = ic->streams[pkt->stream_index];
  572. if (pkt->pts != AV_NOPTS_VALUE) {
  573. end_time = (int64_t)((double)pkt->pts * ic->pts_num * (double)AV_TIME_BASE / ic->pts_den);
  574. duration = end_time - st->start_time;
  575. if (duration > 0) {
  576. if (st->duration == AV_NOPTS_VALUE ||
  577. st->duration < duration)
  578. st->duration = duration;
  579. }
  580. }
  581. av_free_packet(pkt);
  582. }
  583. /* estimate total duration */
  584. end_time = MININT64;
  585. for(i = 0;i < ic->nb_streams; i++) {
  586. st = ic->streams[i];
  587. if (st->duration != AV_NOPTS_VALUE) {
  588. end_time1 = st->start_time + st->duration;
  589. if (end_time1 > end_time)
  590. end_time = end_time1;
  591. }
  592. }
  593. /* update start_time (new stream may have been created, so we do
  594. it at the end */
  595. if (ic->start_time != AV_NOPTS_VALUE) {
  596. for(i = 0; i < ic->nb_streams; i++) {
  597. st = ic->streams[i];
  598. if (st->start_time == AV_NOPTS_VALUE)
  599. st->start_time = ic->start_time;
  600. }
  601. }
  602. if (end_time != MININT64) {
  603. /* put dummy values for duration if needed */
  604. for(i = 0;i < ic->nb_streams; i++) {
  605. st = ic->streams[i];
  606. if (st->duration == AV_NOPTS_VALUE &&
  607. st->start_time != AV_NOPTS_VALUE)
  608. st->duration = end_time - st->start_time;
  609. }
  610. ic->duration = end_time - ic->start_time;
  611. }
  612. url_fseek(&ic->pb, 0, SEEK_SET);
  613. }
  614. static void av_estimate_timings(AVFormatContext *ic)
  615. {
  616. URLContext *h;
  617. int64_t file_size;
  618. /* get the file size, if possible */
  619. if (ic->iformat->flags & AVFMT_NOFILE) {
  620. file_size = 0;
  621. } else {
  622. h = url_fileno(&ic->pb);
  623. file_size = url_filesize(h);
  624. if (file_size < 0)
  625. file_size = 0;
  626. }
  627. ic->file_size = file_size;
  628. if (ic->iformat == &mpegps_demux) {
  629. /* get accurate estimate from the PTSes */
  630. av_estimate_timings_from_pts(ic);
  631. } else if (av_has_timings(ic)) {
  632. /* at least one components has timings - we use them for all
  633. the components */
  634. fill_all_stream_timings(ic);
  635. } else {
  636. /* less precise: use bit rate info */
  637. av_estimate_timings_from_bit_rate(ic);
  638. }
  639. av_update_stream_timings(ic);
  640. #if 0
  641. {
  642. int i;
  643. AVStream *st;
  644. for(i = 0;i < ic->nb_streams; i++) {
  645. st = ic->streams[i];
  646. printf("%d: start_time: %0.3f duration: %0.3f\n",
  647. i, (double)st->start_time / AV_TIME_BASE,
  648. (double)st->duration / AV_TIME_BASE);
  649. }
  650. printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
  651. (double)ic->start_time / AV_TIME_BASE,
  652. (double)ic->duration / AV_TIME_BASE,
  653. ic->bit_rate / 1000);
  654. }
  655. #endif
  656. }
  657. /* state for codec information */
  658. #define CSTATE_NOTFOUND 0
  659. #define CSTATE_DECODING 1
  660. #define CSTATE_FOUND 2
  661. static int has_codec_parameters(AVCodecContext *enc)
  662. {
  663. int val;
  664. switch(enc->codec_type) {
  665. case CODEC_TYPE_AUDIO:
  666. val = enc->sample_rate;
  667. break;
  668. case CODEC_TYPE_VIDEO:
  669. val = enc->width;
  670. break;
  671. default:
  672. val = 1;
  673. break;
  674. }
  675. return (val != 0);
  676. }
  677. /**
  678. * Read the beginning of a media file to get stream information. This
  679. * is useful for file formats with no headers such as MPEG. This
  680. * function also compute the real frame rate in case of mpeg2 repeat
  681. * frame mode.
  682. *
  683. * @param ic media file handle
  684. * @return >=0 if OK. AVERROR_xxx if error.
  685. */
  686. int av_find_stream_info(AVFormatContext *ic)
  687. {
  688. int i, count, ret, got_picture, size, read_size;
  689. AVCodec *codec;
  690. AVStream *st;
  691. AVPacket *pkt;
  692. AVFrame picture;
  693. AVPacketList *pktl=NULL, **ppktl;
  694. short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
  695. uint8_t *ptr;
  696. int min_read_size, max_read_size;
  697. /* typical mpeg ts rate is 40 Mbits. DVD rate is about 10
  698. Mbits. We read at most 0.2 second of file to find all streams */
  699. /* XXX: base it on stream bitrate when possible */
  700. if (ic->iformat == &mpegts_demux) {
  701. /* maximum number of bytes we accept to read to find all the streams
  702. in a file */
  703. min_read_size = 6000000;
  704. } else {
  705. min_read_size = 250000;
  706. }
  707. /* max read size is 2 seconds of video max */
  708. max_read_size = min_read_size * 10;
  709. /* set initial codec state */
  710. for(i=0;i<ic->nb_streams;i++) {
  711. st = ic->streams[i];
  712. if (has_codec_parameters(&st->codec))
  713. st->codec_info_state = CSTATE_FOUND;
  714. else
  715. st->codec_info_state = CSTATE_NOTFOUND;
  716. st->codec_info_nb_repeat_frames = 0;
  717. st->codec_info_nb_real_frames = 0;
  718. }
  719. count = 0;
  720. read_size = 0;
  721. ppktl = &ic->packet_buffer;
  722. for(;;) {
  723. /* check if one codec still needs to be handled */
  724. for(i=0;i<ic->nb_streams;i++) {
  725. st = ic->streams[i];
  726. if (st->codec_info_state != CSTATE_FOUND)
  727. break;
  728. }
  729. if (i == ic->nb_streams) {
  730. /* NOTE: if the format has no header, then we need to read
  731. some packets to get most of the streams, so we cannot
  732. stop here */
  733. if (!(ic->iformat->flags & AVFMT_NOHEADER) ||
  734. read_size >= min_read_size) {
  735. /* if we found the info for all the codecs, we can stop */
  736. ret = count;
  737. break;
  738. }
  739. } else {
  740. /* we did not get all the codec info, but we read too much data */
  741. if (read_size >= max_read_size) {
  742. ret = count;
  743. break;
  744. }
  745. }
  746. pktl = av_mallocz(sizeof(AVPacketList));
  747. if (!pktl) {
  748. ret = AVERROR_NOMEM;
  749. break;
  750. }
  751. /* add the packet in the buffered packet list */
  752. *ppktl = pktl;
  753. ppktl = &pktl->next;
  754. /* NOTE: a new stream can be added there if no header in file
  755. (AVFMT_NOHEADER) */
  756. pkt = &pktl->pkt;
  757. if (ic->iformat->read_packet(ic, pkt) < 0) {
  758. /* EOF or error */
  759. ret = -1; /* we could not have all the codec parameters before EOF */
  760. if ((ic->iformat->flags & AVFMT_NOHEADER) &&
  761. i == ic->nb_streams)
  762. ret = 0;
  763. break;
  764. }
  765. read_size += pkt->size;
  766. /* open new codecs */
  767. for(i=0;i<ic->nb_streams;i++) {
  768. st = ic->streams[i];
  769. if (st->codec_info_state == CSTATE_NOTFOUND) {
  770. /* set to found in case of error */
  771. st->codec_info_state = CSTATE_FOUND;
  772. codec = avcodec_find_decoder(st->codec.codec_id);
  773. if (codec) {
  774. if(codec->capabilities & CODEC_CAP_TRUNCATED)
  775. st->codec.flags |= CODEC_FLAG_TRUNCATED;
  776. ret = avcodec_open(&st->codec, codec);
  777. if (ret >= 0)
  778. st->codec_info_state = CSTATE_DECODING;
  779. }
  780. }
  781. }
  782. st = ic->streams[pkt->stream_index];
  783. if (st->codec_info_state == CSTATE_DECODING) {
  784. /* decode the data and update codec parameters */
  785. ptr = pkt->data;
  786. size = pkt->size;
  787. while (size > 0) {
  788. switch(st->codec.codec_type) {
  789. case CODEC_TYPE_VIDEO:
  790. ret = avcodec_decode_video(&st->codec, &picture,
  791. &got_picture, ptr, size);
  792. break;
  793. case CODEC_TYPE_AUDIO:
  794. ret = avcodec_decode_audio(&st->codec, samples,
  795. &got_picture, ptr, size);
  796. break;
  797. default:
  798. ret = -1;
  799. break;
  800. }
  801. if (ret < 0) {
  802. /* if error, simply ignore because another packet
  803. may be OK */
  804. break;
  805. }
  806. if (got_picture) {
  807. /* we got the parameters - now we can stop
  808. examining this stream */
  809. /* XXX: add a codec info so that we can decide if
  810. the codec can repeat frames */
  811. if (st->codec.codec_id == CODEC_ID_MPEG1VIDEO &&
  812. ic->iformat != &mpegts_demux &&
  813. st->codec.sub_id == 2) {
  814. /* for mpeg2 video, we want to know the real
  815. frame rate, so we decode 40 frames. In mpeg
  816. TS case we do not do it because it would be
  817. too long */
  818. st->codec_info_nb_real_frames++;
  819. st->codec_info_nb_repeat_frames += st->codec.coded_frame->repeat_pict;
  820. #if 0
  821. /* XXX: testing */
  822. if ((st->codec_info_nb_real_frames % 24) == 23) {
  823. st->codec_info_nb_repeat_frames += 2;
  824. }
  825. #endif
  826. /* stop after 40 frames */
  827. if (st->codec_info_nb_real_frames >= 40) {
  828. av_reduce(
  829. &st->r_frame_rate,
  830. &st->r_frame_rate_base,
  831. (int64_t)st->codec.frame_rate * st->codec_info_nb_real_frames,
  832. (st->codec_info_nb_real_frames + (st->codec_info_nb_repeat_frames >> 1)) * st->codec.frame_rate_base,
  833. 1<<30);
  834. goto close_codec;
  835. }
  836. } else {
  837. close_codec:
  838. st->codec_info_state = CSTATE_FOUND;
  839. avcodec_close(&st->codec);
  840. break;
  841. }
  842. }
  843. ptr += ret;
  844. size -= ret;
  845. }
  846. }
  847. count++;
  848. }
  849. /* close each codec if there are opened */
  850. for(i=0;i<ic->nb_streams;i++) {
  851. st = ic->streams[i];
  852. if (st->codec_info_state == CSTATE_DECODING)
  853. avcodec_close(&st->codec);
  854. }
  855. /* set real frame rate info */
  856. for(i=0;i<ic->nb_streams;i++) {
  857. st = ic->streams[i];
  858. if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
  859. if (!st->r_frame_rate){
  860. st->r_frame_rate = st->codec.frame_rate;
  861. st->r_frame_rate_base = st->codec.frame_rate_base;
  862. }
  863. }
  864. }
  865. av_estimate_timings(ic);
  866. return ret;
  867. }
  868. /**
  869. * Close a media file (but not its codecs)
  870. *
  871. * @param s media file handle
  872. */
  873. void av_close_input_file(AVFormatContext *s)
  874. {
  875. int i, must_open_file;
  876. if (s->iformat->read_close)
  877. s->iformat->read_close(s);
  878. for(i=0;i<s->nb_streams;i++) {
  879. av_free(s->streams[i]);
  880. }
  881. if (s->packet_buffer) {
  882. AVPacketList *p, *p1;
  883. p = s->packet_buffer;
  884. while (p != NULL) {
  885. p1 = p->next;
  886. av_free_packet(&p->pkt);
  887. av_free(p);
  888. p = p1;
  889. }
  890. s->packet_buffer = NULL;
  891. }
  892. must_open_file = 1;
  893. if ((s->iformat->flags & AVFMT_NOFILE)
  894. #ifdef CONFIG_NETWORK
  895. || (s->iformat == &rtp_demux && !strcmp(s->filename, "null"))
  896. #endif
  897. ) {
  898. must_open_file = 0;
  899. }
  900. if (must_open_file) {
  901. url_fclose(&s->pb);
  902. }
  903. av_freep(&s->priv_data);
  904. av_free(s);
  905. }
  906. /**
  907. * Add a new stream to a media file. Can only be called in the
  908. * read_header function. If the flag AVFMT_NOHEADER is in the format
  909. * description, then new streams can be added in read_packet too.
  910. *
  911. *
  912. * @param s media file handle
  913. * @param id file format dependent stream id
  914. */
  915. AVStream *av_new_stream(AVFormatContext *s, int id)
  916. {
  917. AVStream *st;
  918. if (s->nb_streams >= MAX_STREAMS)
  919. return NULL;
  920. st = av_mallocz(sizeof(AVStream));
  921. if (!st)
  922. return NULL;
  923. avcodec_get_context_defaults(&st->codec);
  924. if (s->iformat) {
  925. /* no default bitrate if decoding */
  926. st->codec.bit_rate = 0;
  927. }
  928. st->index = s->nb_streams;
  929. st->id = id;
  930. st->start_time = AV_NOPTS_VALUE;
  931. st->duration = AV_NOPTS_VALUE;
  932. s->streams[s->nb_streams++] = st;
  933. return st;
  934. }
  935. /************************************************************/
  936. /* output media file */
  937. int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
  938. {
  939. int ret;
  940. if (s->oformat->priv_data_size > 0) {
  941. s->priv_data = av_mallocz(s->oformat->priv_data_size);
  942. if (!s->priv_data)
  943. return AVERROR_NOMEM;
  944. } else
  945. s->priv_data = NULL;
  946. if (s->oformat->set_parameters) {
  947. ret = s->oformat->set_parameters(s, ap);
  948. if (ret < 0)
  949. return ret;
  950. }
  951. return 0;
  952. }
  953. /**
  954. * allocate the stream private data and write the stream header to an
  955. * output media file
  956. *
  957. * @param s media file handle
  958. * @return 0 if OK. AVERROR_xxx if error.
  959. */
  960. int av_write_header(AVFormatContext *s)
  961. {
  962. int ret, i;
  963. AVStream *st;
  964. /* default pts settings is MPEG like */
  965. av_set_pts_info(s, 33, 1, 90000);
  966. ret = s->oformat->write_header(s);
  967. if (ret < 0)
  968. return ret;
  969. /* init PTS generation */
  970. for(i=0;i<s->nb_streams;i++) {
  971. st = s->streams[i];
  972. switch (st->codec.codec_type) {
  973. case CODEC_TYPE_AUDIO:
  974. av_frac_init(&st->pts, 0, 0,
  975. (int64_t)s->pts_num * st->codec.sample_rate);
  976. break;
  977. case CODEC_TYPE_VIDEO:
  978. av_frac_init(&st->pts, 0, 0,
  979. (int64_t)s->pts_num * st->codec.frame_rate);
  980. break;
  981. default:
  982. break;
  983. }
  984. }
  985. return 0;
  986. }
  987. /**
  988. * Write a packet to an output media file. The packet shall contain
  989. * one audio or video frame.
  990. *
  991. * @param s media file handle
  992. * @param stream_index stream index
  993. * @param buf buffer containing the frame data
  994. * @param size size of buffer
  995. * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
  996. */
  997. int av_write_frame(AVFormatContext *s, int stream_index, const uint8_t *buf,
  998. int size)
  999. {
  1000. AVStream *st;
  1001. int64_t pts_mask;
  1002. int ret, frame_size;
  1003. st = s->streams[stream_index];
  1004. pts_mask = (1LL << s->pts_wrap_bits) - 1;
  1005. ret = s->oformat->write_packet(s, stream_index, (uint8_t *)buf, size,
  1006. st->pts.val & pts_mask);
  1007. if (ret < 0)
  1008. return ret;
  1009. /* update pts */
  1010. switch (st->codec.codec_type) {
  1011. case CODEC_TYPE_AUDIO:
  1012. if (st->codec.frame_size <= 1) {
  1013. frame_size = size / st->codec.channels;
  1014. /* specific hack for pcm codecs because no frame size is provided */
  1015. switch(st->codec.codec_id) {
  1016. case CODEC_ID_PCM_S16LE:
  1017. case CODEC_ID_PCM_S16BE:
  1018. case CODEC_ID_PCM_U16LE:
  1019. case CODEC_ID_PCM_U16BE:
  1020. frame_size >>= 1;
  1021. break;
  1022. default:
  1023. break;
  1024. }
  1025. } else {
  1026. frame_size = st->codec.frame_size;
  1027. }
  1028. av_frac_add(&st->pts,
  1029. (int64_t)s->pts_den * frame_size);
  1030. break;
  1031. case CODEC_TYPE_VIDEO:
  1032. av_frac_add(&st->pts,
  1033. (int64_t)s->pts_den * st->codec.frame_rate_base);
  1034. break;
  1035. default:
  1036. break;
  1037. }
  1038. return ret;
  1039. }
  1040. /**
  1041. * write the stream trailer to an output media file and and free the
  1042. * file private data.
  1043. *
  1044. * @param s media file handle
  1045. * @return 0 if OK. AVERROR_xxx if error. */
  1046. int av_write_trailer(AVFormatContext *s)
  1047. {
  1048. int ret;
  1049. ret = s->oformat->write_trailer(s);
  1050. av_freep(&s->priv_data);
  1051. return ret;
  1052. }
  1053. /* "user interface" functions */
  1054. void dump_format(AVFormatContext *ic,
  1055. int index,
  1056. const char *url,
  1057. int is_output)
  1058. {
  1059. int i, flags;
  1060. char buf[256];
  1061. fprintf(stderr, "%s #%d, %s, %s '%s':\n",
  1062. is_output ? "Output" : "Input",
  1063. index,
  1064. is_output ? ic->oformat->name : ic->iformat->name,
  1065. is_output ? "to" : "from", url);
  1066. if (!is_output) {
  1067. fprintf(stderr, " Duration: ");
  1068. if (ic->duration != AV_NOPTS_VALUE) {
  1069. int hours, mins, secs, us;
  1070. secs = ic->duration / AV_TIME_BASE;
  1071. us = ic->duration % AV_TIME_BASE;
  1072. mins = secs / 60;
  1073. secs %= 60;
  1074. hours = mins / 60;
  1075. mins %= 60;
  1076. fprintf(stderr, "%02d:%02d:%02d.%01d", hours, mins, secs,
  1077. (10 * us) / AV_TIME_BASE);
  1078. } else {
  1079. fprintf(stderr, "N/A");
  1080. }
  1081. fprintf(stderr, ", bitrate: ");
  1082. if (ic->bit_rate) {
  1083. fprintf(stderr,"%d kb/s", ic->bit_rate / 1000);
  1084. } else {
  1085. fprintf(stderr, "N/A");
  1086. }
  1087. fprintf(stderr, "\n");
  1088. }
  1089. for(i=0;i<ic->nb_streams;i++) {
  1090. AVStream *st = ic->streams[i];
  1091. avcodec_string(buf, sizeof(buf), &st->codec, is_output);
  1092. fprintf(stderr, " Stream #%d.%d", index, i);
  1093. /* the pid is an important information, so we display it */
  1094. /* XXX: add a generic system */
  1095. if (is_output)
  1096. flags = ic->oformat->flags;
  1097. else
  1098. flags = ic->iformat->flags;
  1099. if (flags & AVFMT_SHOW_IDS) {
  1100. fprintf(stderr, "[0x%x]", st->id);
  1101. }
  1102. fprintf(stderr, ": %s\n", buf);
  1103. }
  1104. }
  1105. typedef struct {
  1106. const char *abv;
  1107. int width, height;
  1108. int frame_rate, frame_rate_base;
  1109. } AbvEntry;
  1110. static AbvEntry frame_abvs[] = {
  1111. { "ntsc", 352, 240, 30000, 1001 },
  1112. { "pal", 352, 288, 25, 1 },
  1113. { "film", 352, 240, 24, 1 },
  1114. { "ntsc-film", 352, 240, 24000, 1001 },
  1115. { "sqcif", 128, 96, 0, 0 },
  1116. { "qcif", 176, 144, 0, 0 },
  1117. { "cif", 352, 288, 0, 0 },
  1118. { "4cif", 704, 576, 0, 0 },
  1119. };
  1120. int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
  1121. {
  1122. int i;
  1123. int n = sizeof(frame_abvs) / sizeof(AbvEntry);
  1124. const char *p;
  1125. int frame_width = 0, frame_height = 0;
  1126. for(i=0;i<n;i++) {
  1127. if (!strcmp(frame_abvs[i].abv, str)) {
  1128. frame_width = frame_abvs[i].width;
  1129. frame_height = frame_abvs[i].height;
  1130. break;
  1131. }
  1132. }
  1133. if (i == n) {
  1134. p = str;
  1135. frame_width = strtol(p, (char **)&p, 10);
  1136. if (*p)
  1137. p++;
  1138. frame_height = strtol(p, (char **)&p, 10);
  1139. }
  1140. if (frame_width <= 0 || frame_height <= 0)
  1141. return -1;
  1142. *width_ptr = frame_width;
  1143. *height_ptr = frame_height;
  1144. return 0;
  1145. }
  1146. int parse_frame_rate(int *frame_rate, int *frame_rate_base, const char *arg)
  1147. {
  1148. int i;
  1149. char* cp;
  1150. /* First, we check our abbreviation table */
  1151. for (i = 0; i < sizeof(frame_abvs)/sizeof(*frame_abvs); ++i)
  1152. if (!strcmp(frame_abvs[i].abv, arg)) {
  1153. *frame_rate = frame_abvs[i].frame_rate;
  1154. *frame_rate_base = frame_abvs[i].frame_rate_base;
  1155. return 0;
  1156. }
  1157. /* Then, we try to parse it as fraction */
  1158. cp = strchr(arg, '/');
  1159. if (cp) {
  1160. char* cpp;
  1161. *frame_rate = strtol(arg, &cpp, 10);
  1162. if (cpp != arg || cpp == cp)
  1163. *frame_rate_base = strtol(cp+1, &cpp, 10);
  1164. else
  1165. *frame_rate = 0;
  1166. }
  1167. else {
  1168. /* Finally we give up and parse it as double */
  1169. *frame_rate_base = DEFAULT_FRAME_RATE_BASE;
  1170. *frame_rate = (int)(strtod(arg, 0) * (*frame_rate_base) + 0.5);
  1171. }
  1172. if (!*frame_rate || !*frame_rate_base)
  1173. return -1;
  1174. else
  1175. return 0;
  1176. }
  1177. int64_t av_gettime(void)
  1178. {
  1179. #ifdef CONFIG_WIN32
  1180. struct _timeb tb;
  1181. _ftime(&tb);
  1182. return ((int64_t)tb.time * int64_t_C(1000) + (int64_t)tb.millitm) * int64_t_C(1000);
  1183. #else
  1184. struct timeval tv;
  1185. gettimeofday(&tv,NULL);
  1186. return (int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
  1187. #endif
  1188. }
  1189. static time_t mktimegm(struct tm *tm)
  1190. {
  1191. time_t t;
  1192. int y = tm->tm_year + 1900, m = tm->tm_mon + 1, d = tm->tm_mday;
  1193. if (m < 3) {
  1194. m += 12;
  1195. y--;
  1196. }
  1197. t = 86400 *
  1198. (d + (153 * m - 457) / 5 + 365 * y + y / 4 - y / 100 + y / 400 - 719469);
  1199. t += 3600 * tm->tm_hour + 60 * tm->tm_min + tm->tm_sec;
  1200. return t;
  1201. }
  1202. /* Syntax:
  1203. * - If not a duration:
  1204. * [{YYYY-MM-DD|YYYYMMDD}]{T| }{HH[:MM[:SS[.m...]]][Z]|HH[MM[SS[.m...]]][Z]}
  1205. * Time is localtime unless Z is suffixed to the end. In this case GMT
  1206. * Return the date in micro seconds since 1970
  1207. * - If duration:
  1208. * HH[:MM[:SS[.m...]]]
  1209. * S+[.m...]
  1210. */
  1211. int64_t parse_date(const char *datestr, int duration)
  1212. {
  1213. const char *p;
  1214. int64_t t;
  1215. struct tm dt;
  1216. int i;
  1217. static const char *date_fmt[] = {
  1218. "%Y-%m-%d",
  1219. "%Y%m%d",
  1220. };
  1221. static const char *time_fmt[] = {
  1222. "%H:%M:%S",
  1223. "%H%M%S",
  1224. };
  1225. const char *q;
  1226. int is_utc, len;
  1227. char lastch;
  1228. time_t now = time(0);
  1229. len = strlen(datestr);
  1230. if (len > 0)
  1231. lastch = datestr[len - 1];
  1232. else
  1233. lastch = '\0';
  1234. is_utc = (lastch == 'z' || lastch == 'Z');
  1235. memset(&dt, 0, sizeof(dt));
  1236. p = datestr;
  1237. q = NULL;
  1238. if (!duration) {
  1239. for (i = 0; i < sizeof(date_fmt) / sizeof(date_fmt[0]); i++) {
  1240. q = strptime(p, date_fmt[i], &dt);
  1241. if (q) {
  1242. break;
  1243. }
  1244. }
  1245. if (!q) {
  1246. if (is_utc) {
  1247. dt = *gmtime(&now);
  1248. } else {
  1249. dt = *localtime(&now);
  1250. }
  1251. dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
  1252. } else {
  1253. p = q;
  1254. }
  1255. if (*p == 'T' || *p == 't' || *p == ' ')
  1256. p++;
  1257. for (i = 0; i < sizeof(time_fmt) / sizeof(time_fmt[0]); i++) {
  1258. q = strptime(p, time_fmt[i], &dt);
  1259. if (q) {
  1260. break;
  1261. }
  1262. }
  1263. } else {
  1264. q = strptime(p, time_fmt[0], &dt);
  1265. if (!q) {
  1266. dt.tm_sec = strtol(p, (char **)&q, 10);
  1267. dt.tm_min = 0;
  1268. dt.tm_hour = 0;
  1269. }
  1270. }
  1271. /* Now we have all the fields that we can get */
  1272. if (!q) {
  1273. if (duration)
  1274. return 0;
  1275. else
  1276. return now * int64_t_C(1000000);
  1277. }
  1278. if (duration) {
  1279. t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
  1280. } else {
  1281. dt.tm_isdst = -1; /* unknown */
  1282. if (is_utc) {
  1283. t = mktimegm(&dt);
  1284. } else {
  1285. t = mktime(&dt);
  1286. }
  1287. }
  1288. t *= 1000000;
  1289. if (*q == '.') {
  1290. int val, n;
  1291. q++;
  1292. for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
  1293. if (!isdigit(*q))
  1294. break;
  1295. val += n * (*q - '0');
  1296. }
  1297. t += val;
  1298. }
  1299. return t;
  1300. }
  1301. /* syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done. Return
  1302. 1 if found */
  1303. int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
  1304. {
  1305. const char *p;
  1306. char tag[128], *q;
  1307. p = info;
  1308. if (*p == '?')
  1309. p++;
  1310. for(;;) {
  1311. q = tag;
  1312. while (*p != '\0' && *p != '=' && *p != '&') {
  1313. if ((q - tag) < sizeof(tag) - 1)
  1314. *q++ = *p;
  1315. p++;
  1316. }
  1317. *q = '\0';
  1318. q = arg;
  1319. if (*p == '=') {
  1320. p++;
  1321. while (*p != '&' && *p != '\0') {
  1322. if ((q - arg) < arg_size - 1) {
  1323. if (*p == '+')
  1324. *q++ = ' ';
  1325. else
  1326. *q++ = *p;
  1327. }
  1328. p++;
  1329. }
  1330. *q = '\0';
  1331. }
  1332. if (!strcmp(tag, tag1))
  1333. return 1;
  1334. if (*p != '&')
  1335. break;
  1336. p++;
  1337. }
  1338. return 0;
  1339. }
  1340. /* Return in 'buf' the path with '%d' replaced by number. Also handles
  1341. the '%0nd' format where 'n' is the total number of digits and
  1342. '%%'. Return 0 if OK, and -1 if format error */
  1343. int get_frame_filename(char *buf, int buf_size,
  1344. const char *path, int number)
  1345. {
  1346. const char *p;
  1347. char *q, buf1[20];
  1348. int nd, len, c, percentd_found;
  1349. q = buf;
  1350. p = path;
  1351. percentd_found = 0;
  1352. for(;;) {
  1353. c = *p++;
  1354. if (c == '\0')
  1355. break;
  1356. if (c == '%') {
  1357. do {
  1358. nd = 0;
  1359. while (isdigit(*p)) {
  1360. nd = nd * 10 + *p++ - '0';
  1361. }
  1362. c = *p++;
  1363. if (c == '*' && nd > 0) {
  1364. // The nd field is actually the modulus
  1365. number = number % nd;
  1366. c = *p++;
  1367. nd = 0;
  1368. }
  1369. } while (isdigit(c));
  1370. switch(c) {
  1371. case '%':
  1372. goto addchar;
  1373. case 'd':
  1374. if (percentd_found)
  1375. goto fail;
  1376. percentd_found = 1;
  1377. snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
  1378. len = strlen(buf1);
  1379. if ((q - buf + len) > buf_size - 1)
  1380. goto fail;
  1381. memcpy(q, buf1, len);
  1382. q += len;
  1383. break;
  1384. default:
  1385. goto fail;
  1386. }
  1387. } else {
  1388. addchar:
  1389. if ((q - buf) < buf_size - 1)
  1390. *q++ = c;
  1391. }
  1392. }
  1393. if (!percentd_found)
  1394. goto fail;
  1395. *q = '\0';
  1396. return 0;
  1397. fail:
  1398. *q = '\0';
  1399. return -1;
  1400. }
  1401. /**
  1402. *
  1403. * Print on stdout a nice hexa dump of a buffer
  1404. * @param buf buffer
  1405. * @param size buffer size
  1406. */
  1407. void av_hex_dump(uint8_t *buf, int size)
  1408. {
  1409. int len, i, j, c;
  1410. for(i=0;i<size;i+=16) {
  1411. len = size - i;
  1412. if (len > 16)
  1413. len = 16;
  1414. printf("%08x ", i);
  1415. for(j=0;j<16;j++) {
  1416. if (j < len)
  1417. printf(" %02x", buf[i+j]);
  1418. else
  1419. printf(" ");
  1420. }
  1421. printf(" ");
  1422. for(j=0;j<len;j++) {
  1423. c = buf[i+j];
  1424. if (c < ' ' || c > '~')
  1425. c = '.';
  1426. printf("%c", c);
  1427. }
  1428. printf("\n");
  1429. }
  1430. }
  1431. void url_split(char *proto, int proto_size,
  1432. char *hostname, int hostname_size,
  1433. int *port_ptr,
  1434. char *path, int path_size,
  1435. const char *url)
  1436. {
  1437. const char *p;
  1438. char *q;
  1439. int port;
  1440. port = -1;
  1441. p = url;
  1442. q = proto;
  1443. while (*p != ':' && *p != '\0') {
  1444. if ((q - proto) < proto_size - 1)
  1445. *q++ = *p;
  1446. p++;
  1447. }
  1448. if (proto_size > 0)
  1449. *q = '\0';
  1450. if (*p == '\0') {
  1451. if (proto_size > 0)
  1452. proto[0] = '\0';
  1453. if (hostname_size > 0)
  1454. hostname[0] = '\0';
  1455. p = url;
  1456. } else {
  1457. p++;
  1458. if (*p == '/')
  1459. p++;
  1460. if (*p == '/')
  1461. p++;
  1462. q = hostname;
  1463. while (*p != ':' && *p != '/' && *p != '?' && *p != '\0') {
  1464. if ((q - hostname) < hostname_size - 1)
  1465. *q++ = *p;
  1466. p++;
  1467. }
  1468. if (hostname_size > 0)
  1469. *q = '\0';
  1470. if (*p == ':') {
  1471. p++;
  1472. port = strtoul(p, (char **)&p, 10);
  1473. }
  1474. }
  1475. if (port_ptr)
  1476. *port_ptr = port;
  1477. pstrcpy(path, path_size, p);
  1478. }
  1479. /**
  1480. * Set the pts for a given stream
  1481. * @param s stream
  1482. * @param pts_wrap_bits number of bits effectively used by the pts
  1483. * (used for wrap control, 33 is the value for MPEG)
  1484. * @param pts_num numerator to convert to seconds (MPEG: 1)
  1485. * @param pts_den denominator to convert to seconds (MPEG: 90000)
  1486. */
  1487. void av_set_pts_info(AVFormatContext *s, int pts_wrap_bits,
  1488. int pts_num, int pts_den)
  1489. {
  1490. s->pts_wrap_bits = pts_wrap_bits;
  1491. s->pts_num = pts_num;
  1492. s->pts_den = pts_den;
  1493. }
  1494. /* fraction handling */
  1495. /**
  1496. * f = val + (num / den) + 0.5. 'num' is normalized so that it is such
  1497. * as 0 <= num < den.
  1498. *
  1499. * @param f fractional number
  1500. * @param val integer value
  1501. * @param num must be >= 0
  1502. * @param den must be >= 1
  1503. */
  1504. void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
  1505. {
  1506. num += (den >> 1);
  1507. if (num >= den) {
  1508. val += num / den;
  1509. num = num % den;
  1510. }
  1511. f->val = val;
  1512. f->num = num;
  1513. f->den = den;
  1514. }
  1515. /* set f to (val + 0.5) */
  1516. void av_frac_set(AVFrac *f, int64_t val)
  1517. {
  1518. f->val = val;
  1519. f->num = f->den >> 1;
  1520. }
  1521. /**
  1522. * Fractionnal addition to f: f = f + (incr / f->den)
  1523. *
  1524. * @param f fractional number
  1525. * @param incr increment, can be positive or negative
  1526. */
  1527. void av_frac_add(AVFrac *f, int64_t incr)
  1528. {
  1529. int64_t num, den;
  1530. num = f->num + incr;
  1531. den = f->den;
  1532. if (num < 0) {
  1533. f->val += num / den;
  1534. num = num % den;
  1535. if (num < 0) {
  1536. num += den;
  1537. f->val--;
  1538. }
  1539. } else if (num >= den) {
  1540. f->val += num / den;
  1541. num = num % den;
  1542. }
  1543. f->num = num;
  1544. }
  1545. /**
  1546. * register a new image format
  1547. * @param img_fmt Image format descriptor
  1548. */
  1549. void av_register_image_format(AVImageFormat *img_fmt)
  1550. {
  1551. AVImageFormat **p;
  1552. p = &first_image_format;
  1553. while (*p != NULL) p = &(*p)->next;
  1554. *p = img_fmt;
  1555. img_fmt->next = NULL;
  1556. }
  1557. /* guess image format */
  1558. AVImageFormat *av_probe_image_format(AVProbeData *pd)
  1559. {
  1560. AVImageFormat *fmt1, *fmt;
  1561. int score, score_max;
  1562. fmt = NULL;
  1563. score_max = 0;
  1564. for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
  1565. if (fmt1->img_probe) {
  1566. score = fmt1->img_probe(pd);
  1567. if (score > score_max) {
  1568. score_max = score;
  1569. fmt = fmt1;
  1570. }
  1571. }
  1572. }
  1573. return fmt;
  1574. }
  1575. AVImageFormat *guess_image_format(const char *filename)
  1576. {
  1577. AVImageFormat *fmt1;
  1578. for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
  1579. if (fmt1->extensions && match_ext(filename, fmt1->extensions))
  1580. return fmt1;
  1581. }
  1582. return NULL;
  1583. }
  1584. /**
  1585. * Read an image from a stream.
  1586. * @param gb byte stream containing the image
  1587. * @param fmt image format, NULL if probing is required
  1588. */
  1589. int av_read_image(ByteIOContext *pb, const char *filename,
  1590. AVImageFormat *fmt,
  1591. int (*alloc_cb)(void *, AVImageInfo *info), void *opaque)
  1592. {
  1593. char buf[PROBE_BUF_SIZE];
  1594. AVProbeData probe_data, *pd = &probe_data;
  1595. offset_t pos;
  1596. int ret;
  1597. if (!fmt) {
  1598. pd->filename = filename;
  1599. pd->buf = buf;
  1600. pos = url_ftell(pb);
  1601. pd->buf_size = get_buffer(pb, buf, PROBE_BUF_SIZE);
  1602. url_fseek(pb, pos, SEEK_SET);
  1603. fmt = av_probe_image_format(pd);
  1604. }
  1605. if (!fmt)
  1606. return AVERROR_NOFMT;
  1607. ret = fmt->img_read(pb, alloc_cb, opaque);
  1608. return ret;
  1609. }
  1610. /**
  1611. * Write an image to a stream.
  1612. * @param pb byte stream for the image output
  1613. * @param fmt image format
  1614. * @param img image data and informations
  1615. */
  1616. int av_write_image(ByteIOContext *pb, AVImageFormat *fmt, AVImageInfo *img)
  1617. {
  1618. return fmt->img_write(pb, img);
  1619. }