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.

2080 lines
65KB

  1. /*
  2. * FFmpeg main
  3. * Copyright (c) 2000,2001 Gerard Lantau
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program 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
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program; if not, write to the Free Software
  17. * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  18. */
  19. #include <stdlib.h>
  20. #include <stdio.h>
  21. #include <unistd.h>
  22. #include <fcntl.h>
  23. #include <sys/ioctl.h>
  24. #include <errno.h>
  25. #include <sys/time.h>
  26. #include <string.h>
  27. #include <sys/poll.h>
  28. #include <termios.h>
  29. #include <ctype.h>
  30. #include "avformat.h"
  31. typedef struct {
  32. const char *name;
  33. int flags;
  34. #define HAS_ARG 0x0001
  35. #define OPT_BOOL 0x0002
  36. #define OPT_EXPERT 0x0004
  37. #define OPT_STRING 0x0008
  38. union {
  39. void (*func_arg)();
  40. int *int_arg;
  41. char **str_arg;
  42. } u;
  43. const char *help;
  44. const char *argname;
  45. } OptionDef;
  46. /* select an input stream for an output stream */
  47. typedef struct AVStreamMap {
  48. int file_index;
  49. int stream_index;
  50. } AVStreamMap;
  51. extern const OptionDef options[];
  52. void show_help(void);
  53. #define MAX_FILES 20
  54. static AVFormatContext *input_files[MAX_FILES];
  55. static int nb_input_files = 0;
  56. static AVFormatContext *output_files[MAX_FILES];
  57. static int nb_output_files = 0;
  58. static AVStreamMap stream_maps[MAX_FILES];
  59. static int nb_stream_maps;
  60. static AVFormat *file_format;
  61. static int frame_width = 160;
  62. static int frame_height = 128;
  63. static int frame_rate = 25 * FRAME_RATE_BASE;
  64. static int video_bit_rate = 200000;
  65. static int video_qscale = 0;
  66. static int video_disable = 0;
  67. static int video_codec_id = CODEC_ID_NONE;
  68. static int same_quality = 0;
  69. static int gop_size = 12;
  70. static int intra_only = 0;
  71. static int audio_sample_rate = 44100;
  72. static int audio_bit_rate = 64000;
  73. static int audio_disable = 0;
  74. static int audio_channels = 1;
  75. static int audio_codec_id = CODEC_ID_NONE;
  76. static INT64 recording_time = 0;
  77. static int file_overwrite = 0;
  78. static char *str_title = NULL;
  79. static char *str_author = NULL;
  80. static char *str_copyright = NULL;
  81. static char *str_comment = NULL;
  82. typedef struct AVOutputStream {
  83. int file_index; /* file index */
  84. int index; /* stream index in the output file */
  85. int source_index; /* AVInputStream index */
  86. AVStream *st; /* stream in the output file */
  87. int encoding_needed; /* true if encoding needed for this stream */
  88. int fifo_packet_rptr; /* read index in the corresponding
  89. avinputstream packet fifo */
  90. /* video only */
  91. AVPicture pict_tmp; /* temporary image for resizing */
  92. int video_resample;
  93. ImgReSampleContext *img_resample_ctx; /* for image resampling */
  94. /* audio only */
  95. int audio_resample;
  96. ReSampleContext *resample; /* for audio resampling */
  97. FifoBuffer fifo; /* for compression: one audio fifo per codec */
  98. } AVOutputStream;
  99. typedef struct AVInputStream {
  100. int file_index;
  101. int index;
  102. AVStream *st;
  103. int discard; /* true if stream data should be discarded */
  104. int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
  105. INT64 pts; /* current pts */
  106. int frame_number; /* current frame */
  107. INT64 sample_index; /* current sample */
  108. } AVInputStream;
  109. typedef struct AVInputFile {
  110. int eof_reached; /* true if eof reached */
  111. int ist_index; /* index of first stream in ist_table */
  112. int buffer_size; /* current total buffer size */
  113. int buffer_size_max; /* buffer size at which we consider we can stop
  114. buffering */
  115. } AVInputFile;
  116. /* init terminal so that we can grab keys */
  117. static struct termios oldtty;
  118. static void term_exit(void)
  119. {
  120. tcsetattr (0, TCSANOW, &oldtty);
  121. }
  122. static void term_init(void)
  123. {
  124. struct termios tty;
  125. tcgetattr (0, &tty);
  126. oldtty = tty;
  127. tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
  128. |INLCR|IGNCR|ICRNL|IXON);
  129. tty.c_oflag |= OPOST;
  130. tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
  131. tty.c_cflag &= ~(CSIZE|PARENB);
  132. tty.c_cflag |= CS8;
  133. tty.c_cc[VMIN] = 1;
  134. tty.c_cc[VTIME] = 0;
  135. tcsetattr (0, TCSANOW, &tty);
  136. atexit(term_exit);
  137. }
  138. /* read a key without blocking */
  139. static int read_key(void)
  140. {
  141. struct timeval tv;
  142. int n;
  143. unsigned char ch;
  144. fd_set rfds;
  145. FD_ZERO(&rfds);
  146. FD_SET(0, &rfds);
  147. tv.tv_sec = 0;
  148. tv.tv_usec = 0;
  149. n = select(1, &rfds, NULL, NULL, &tv);
  150. if (n > 0) {
  151. if (read(0, &ch, 1) == 1)
  152. return ch;
  153. }
  154. return -1;
  155. }
  156. #define AUDIO_FIFO_SIZE 8192
  157. /* main loop for grabbing */
  158. int av_grab(AVFormatContext *s)
  159. {
  160. UINT8 audio_buf[AUDIO_FIFO_SIZE/2];
  161. UINT8 audio_buf1[AUDIO_FIFO_SIZE/2];
  162. UINT8 audio_out[AUDIO_FIFO_SIZE/2];
  163. UINT8 video_buffer[128*1024];
  164. char buf[256];
  165. short *samples;
  166. URLContext *audio_handle = NULL, *video_handle = NULL;
  167. int ret;
  168. AVCodecContext *enc, *first_video_enc = NULL;
  169. int frame_size, frame_bytes;
  170. int use_audio, use_video;
  171. int frame_rate, sample_rate, channels;
  172. int width, height, frame_number, i, pix_fmt = 0;
  173. AVOutputStream *ost_table[s->nb_streams], *ost;
  174. UINT8 *picture_in_buf = NULL, *picture_420p = NULL;
  175. int audio_fifo_size = 0, picture_size = 0;
  176. INT64 time_start;
  177. /* init output stream info */
  178. for(i=0;i<s->nb_streams;i++)
  179. ost_table[i] = NULL;
  180. /* output stream init */
  181. for(i=0;i<s->nb_streams;i++) {
  182. ost = av_mallocz(sizeof(AVOutputStream));
  183. if (!ost)
  184. goto fail;
  185. ost->index = i;
  186. ost->st = s->streams[i];
  187. ost_table[i] = ost;
  188. }
  189. use_audio = 0;
  190. use_video = 0;
  191. frame_rate = 0;
  192. sample_rate = 0;
  193. frame_size = 0;
  194. channels = 1;
  195. width = 0;
  196. height = 0;
  197. frame_number = 0;
  198. for(i=0;i<s->nb_streams;i++) {
  199. AVCodec *codec;
  200. ost = ost_table[i];
  201. enc = &ost->st->codec;
  202. codec = avcodec_find_encoder(enc->codec_id);
  203. if (!codec) {
  204. fprintf(stderr, "Unknown codec\n");
  205. return -1;
  206. }
  207. if (avcodec_open(enc, codec) < 0) {
  208. fprintf(stderr, "Incorrect encode parameters\n");
  209. return -1;
  210. }
  211. switch(enc->codec_type) {
  212. case CODEC_TYPE_AUDIO:
  213. use_audio = 1;
  214. if (enc->sample_rate > sample_rate)
  215. sample_rate = enc->sample_rate;
  216. if (enc->frame_size > frame_size)
  217. frame_size = enc->frame_size;
  218. if (enc->channels > channels)
  219. channels = enc->channels;
  220. break;
  221. case CODEC_TYPE_VIDEO:
  222. if (!first_video_enc)
  223. first_video_enc = enc;
  224. use_video = 1;
  225. if (enc->frame_rate > frame_rate)
  226. frame_rate = enc->frame_rate;
  227. if (enc->width > width)
  228. width = enc->width;
  229. if (enc->height > height)
  230. height = enc->height;
  231. break;
  232. }
  233. }
  234. /* audio */
  235. samples = NULL;
  236. if (use_audio) {
  237. snprintf(buf, sizeof(buf), "audio:%d,%d", sample_rate, channels);
  238. ret = url_open(&audio_handle, buf, URL_RDONLY);
  239. if (ret < 0) {
  240. fprintf(stderr, "Could not open audio device: disabling audio capture\n");
  241. use_audio = 0;
  242. } else {
  243. URLFormat f;
  244. /* read back exact grab parameters */
  245. if (url_getformat(audio_handle, &f) < 0) {
  246. fprintf(stderr, "could not read back video grab parameters\n");
  247. goto fail;
  248. }
  249. sample_rate = f.sample_rate;
  250. channels = f.channels;
  251. audio_fifo_size = ((AUDIO_FIFO_SIZE / 2) / audio_handle->packet_size) *
  252. audio_handle->packet_size;
  253. fprintf(stderr, "Audio sampling: %d Hz, %s\n",
  254. sample_rate, channels == 2 ? "stereo" : "mono");
  255. }
  256. }
  257. /* video */
  258. if (use_video) {
  259. snprintf(buf, sizeof(buf), "video:%d,%d,%f",
  260. width, height, (float)frame_rate / FRAME_RATE_BASE);
  261. ret = url_open(&video_handle, buf, URL_RDONLY);
  262. if (ret < 0) {
  263. fprintf(stderr,"Could not init video 4 linux capture: disabling video capture\n");
  264. use_video = 0;
  265. } else {
  266. URLFormat f;
  267. const char *pix_fmt_str;
  268. /* read back exact grab parameters */
  269. if (url_getformat(video_handle, &f) < 0) {
  270. fprintf(stderr, "could not read back video grab parameters\n");
  271. goto fail;
  272. }
  273. width = f.width;
  274. height = f.height;
  275. pix_fmt = f.pix_fmt;
  276. switch(pix_fmt) {
  277. case PIX_FMT_YUV420P:
  278. pix_fmt_str = "420P";
  279. break;
  280. case PIX_FMT_YUV422:
  281. pix_fmt_str = "422";
  282. break;
  283. case PIX_FMT_RGB24:
  284. pix_fmt_str = "RGB24";
  285. break;
  286. case PIX_FMT_BGR24:
  287. pix_fmt_str = "BGR24";
  288. break;
  289. default:
  290. pix_fmt_str = "???";
  291. break;
  292. }
  293. picture_size = video_handle->packet_size;
  294. picture_in_buf = malloc(picture_size);
  295. if (!picture_in_buf)
  296. goto fail;
  297. /* allocate a temporary picture if not grabbing in 420P format */
  298. if (pix_fmt != PIX_FMT_YUV420P) {
  299. picture_420p = malloc((width * height * 3) / 2);
  300. }
  301. fprintf(stderr, "Video sampling: %dx%d, %s format, %0.2f fps\n",
  302. width, height, pix_fmt_str, (float)frame_rate / FRAME_RATE_BASE);
  303. }
  304. }
  305. if (!use_video && !use_audio) {
  306. fprintf(stderr,"Could not open grab devices : exiting\n");
  307. exit(1);
  308. }
  309. /* init built in conversion functions */
  310. for(i=0;i<s->nb_streams;i++) {
  311. ost = ost_table[i];
  312. enc = &ost->st->codec;
  313. switch(enc->codec_type) {
  314. case CODEC_TYPE_AUDIO:
  315. ost->audio_resample = 0;
  316. if ((enc->channels != channels ||
  317. enc->sample_rate != sample_rate)) {
  318. ost->audio_resample = 1;
  319. ost->resample = audio_resample_init(enc->channels, channels,
  320. enc->sample_rate, sample_rate);
  321. }
  322. if (fifo_init(&ost->fifo, (2 * audio_fifo_size * enc->sample_rate) /
  323. sample_rate))
  324. goto fail;
  325. break;
  326. case CODEC_TYPE_VIDEO:
  327. ost->video_resample = 0;
  328. if (enc->width != width ||
  329. enc->height != height) {
  330. UINT8 *buf;
  331. ost->video_resample = 1;
  332. buf = malloc((enc->width * enc->height * 3) / 2);
  333. if (!buf)
  334. goto fail;
  335. ost->pict_tmp.data[0] = buf;
  336. ost->pict_tmp.data[1] = buf + enc->width * height;
  337. ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (enc->width * height) / 4;
  338. ost->pict_tmp.linesize[0] = enc->width;
  339. ost->pict_tmp.linesize[1] = enc->width / 2;
  340. ost->pict_tmp.linesize[2] = enc->width / 2;
  341. ost->img_resample_ctx = img_resample_init(
  342. ost->st->codec.width, ost->st->codec.height,
  343. width, height);
  344. }
  345. }
  346. }
  347. fprintf(stderr, "Press [q] to stop encoding\n");
  348. s->format->write_header(s);
  349. time_start = gettime();
  350. term_init();
  351. for(;;) {
  352. /* if 'q' pressed, exits */
  353. if (read_key() == 'q')
  354. break;
  355. /* read & compress audio frames */
  356. if (use_audio) {
  357. int ret, nb_samples, nb_samples_out;
  358. UINT8 *buftmp;
  359. for(;;) {
  360. ret = url_read(audio_handle, audio_buf, audio_fifo_size);
  361. if (ret <= 0)
  362. break;
  363. /* fill each codec fifo by doing the right sample
  364. rate conversion. This is not optimal because we
  365. do too much work, but it is easy to do */
  366. nb_samples = ret / (channels * 2);
  367. for(i=0;i<s->nb_streams;i++) {
  368. ost = ost_table[i];
  369. enc = &ost->st->codec;
  370. if (enc->codec_type == CODEC_TYPE_AUDIO) {
  371. /* rate & stereo convertion */
  372. if (!ost->audio_resample) {
  373. buftmp = audio_buf;
  374. nb_samples_out = nb_samples;
  375. } else {
  376. buftmp = audio_buf1;
  377. nb_samples_out = audio_resample(ost->resample,
  378. (short *)buftmp, (short *)audio_buf,
  379. nb_samples);
  380. }
  381. fifo_write(&ost->fifo, buftmp, nb_samples_out * enc->channels * 2,
  382. &ost->fifo.wptr);
  383. }
  384. }
  385. /* compress as many frame as possible with each audio codec */
  386. for(i=0;i<s->nb_streams;i++) {
  387. ost = ost_table[i];
  388. enc = &ost->st->codec;
  389. if (enc->codec_type == CODEC_TYPE_AUDIO) {
  390. frame_bytes = enc->frame_size * 2 * enc->channels;
  391. while (fifo_read(&ost->fifo, audio_buf,
  392. frame_bytes, &ost->fifo.rptr) == 0) {
  393. ret = avcodec_encode_audio(enc,
  394. audio_out, sizeof(audio_out),
  395. (short *)audio_buf);
  396. s->format->write_packet(s, ost->index, audio_out, ret);
  397. }
  398. }
  399. }
  400. }
  401. }
  402. if (use_video) {
  403. AVPicture *picture1;
  404. AVPicture picture;
  405. UINT8 *pict_buffer;
  406. ret = url_read(video_handle, picture_in_buf, picture_size);
  407. if (ret < 0)
  408. break;
  409. if (pix_fmt != PIX_FMT_YUV420P) {
  410. pict_buffer = picture_420p;
  411. img_convert_to_yuv420(pict_buffer, picture_in_buf, pix_fmt, width, height);
  412. } else {
  413. pict_buffer = picture_in_buf;
  414. }
  415. /* build a picture storage */
  416. picture.data[0] = pict_buffer;
  417. picture.data[1] = picture.data[0] + width * height;
  418. picture.data[2] = picture.data[1] + (width * height) / 4;
  419. picture.linesize[0] = width;
  420. picture.linesize[1] = width / 2;
  421. picture.linesize[2] = width / 2;
  422. for(i=0;i<s->nb_streams;i++) {
  423. ost = ost_table[i];
  424. enc = &ost->st->codec;
  425. if (enc->codec_type == CODEC_TYPE_VIDEO) {
  426. int n1, n2, nb;
  427. /* feed each codec with its requested frame rate */
  428. n1 = ((INT64)frame_number * enc->frame_rate) / frame_rate;
  429. n2 = (((INT64)frame_number + 1) * enc->frame_rate) / frame_rate;
  430. nb = n2 - n1;
  431. if (nb > 0) {
  432. /* resize the picture if needed */
  433. if (ost->video_resample) {
  434. picture1 = &ost->pict_tmp;
  435. img_resample(ost->img_resample_ctx,
  436. picture1, &picture);
  437. } else {
  438. picture1 = &picture;
  439. }
  440. ret = avcodec_encode_video(enc, video_buffer,
  441. sizeof(video_buffer),
  442. picture1);
  443. s->format->write_packet(s, ost->index, video_buffer, ret);
  444. }
  445. }
  446. }
  447. frame_number++;
  448. }
  449. /* write report */
  450. {
  451. char buf[1024];
  452. INT64 total_size;
  453. float ti, bitrate;
  454. static float last_ti;
  455. INT64 ti1;
  456. total_size = url_ftell(&s->pb);
  457. ti1 = gettime() - time_start;
  458. /* check elapsed time */
  459. if (recording_time && ti1 >= recording_time)
  460. break;
  461. ti = ti1 / 1000000.0;
  462. if (ti < 0.1)
  463. ti = 0.1;
  464. /* dispaly twice per second */
  465. if ((ti - last_ti) >= 0.5) {
  466. last_ti = ti;
  467. bitrate = (int)((total_size * 8) / ti / 1000.0);
  468. buf[0] = '\0';
  469. if (use_video) {
  470. sprintf(buf + strlen(buf), "frame=%5d fps=%4.1f q=%2d ",
  471. frame_number, (float)frame_number / ti, first_video_enc->quality);
  472. }
  473. sprintf(buf + strlen(buf), "size=%8LdkB time=%0.1f bitrate=%6.1fkbits/s",
  474. total_size / 1024, ti, bitrate);
  475. fprintf(stderr, "%s \r", buf);
  476. fflush(stderr);
  477. }
  478. }
  479. }
  480. term_exit();
  481. for(i=0;i<s->nb_streams;i++) {
  482. ost = ost_table[i];
  483. enc = &ost->st->codec;
  484. avcodec_close(enc);
  485. }
  486. s->format->write_trailer(s);
  487. if (audio_handle)
  488. url_close(audio_handle);
  489. if (video_handle)
  490. url_close(video_handle);
  491. /* write report */
  492. {
  493. float ti, bitrate;
  494. INT64 total_size;
  495. total_size = url_ftell(&s->pb);
  496. ti = (gettime() - time_start) / 1000000.0;
  497. if (ti < 0.1)
  498. ti = 0.1;
  499. bitrate = (int)((total_size * 8) / ti / 1000.0);
  500. fprintf(stderr, "\033[K\nTotal time = %0.1f s, %Ld KBytes, %0.1f kbits/s\n",
  501. ti, total_size / 1024, bitrate);
  502. if (use_video) {
  503. fprintf(stderr, "Total frames = %d\n", frame_number);
  504. }
  505. }
  506. ret = 0;
  507. fail1:
  508. if (picture_in_buf)
  509. free(picture_in_buf);
  510. if (picture_420p)
  511. free(picture_420p);
  512. for(i=0;i<s->nb_streams;i++) {
  513. ost = ost_table[i];
  514. if (ost) {
  515. if (ost->fifo.buffer)
  516. fifo_free(&ost->fifo);
  517. if (ost->pict_tmp.data[0])
  518. free(ost->pict_tmp.data[0]);
  519. if (ost->video_resample)
  520. img_resample_close(ost->img_resample_ctx);
  521. if (ost->audio_resample)
  522. audio_resample_close(ost->resample);
  523. free(ost);
  524. }
  525. }
  526. return ret;
  527. fail:
  528. ret = -ENOMEM;
  529. goto fail1;
  530. }
  531. int read_ffserver_streams(AVFormatContext *s, const char *filename)
  532. {
  533. int i;
  534. AVFormatContext *ic;
  535. ic = av_open_input_file(filename, FFM_PACKET_SIZE);
  536. if (!ic)
  537. return -EIO;
  538. /* copy stream format */
  539. s->nb_streams = ic->nb_streams;
  540. for(i=0;i<ic->nb_streams;i++) {
  541. AVStream *st;
  542. st = av_mallocz(sizeof(AVFormatContext));
  543. memcpy(st, ic->streams[i], sizeof(AVStream));
  544. s->streams[i] = st;
  545. }
  546. av_close_input_file(ic);
  547. return 0;
  548. }
  549. #define MAX_AUDIO_PACKET_SIZE 16384
  550. static void do_audio_out(AVFormatContext *s,
  551. AVOutputStream *ost,
  552. AVInputStream *ist,
  553. unsigned char *buf, int size)
  554. {
  555. UINT8 *buftmp;
  556. UINT8 audio_buf[2*MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it */
  557. UINT8 audio_out[MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it */
  558. int size_out, frame_bytes, ret;
  559. AVCodecContext *enc;
  560. enc = &ost->st->codec;
  561. if (ost->audio_resample) {
  562. buftmp = audio_buf;
  563. size_out = audio_resample(ost->resample,
  564. (short *)buftmp, (short *)buf,
  565. size / (ist->st->codec.channels * 2));
  566. size_out = size_out * enc->channels * 2;
  567. } else {
  568. buftmp = buf;
  569. size_out = size;
  570. }
  571. /* now encode as many frames as possible */
  572. if (enc->codec_id != CODEC_ID_PCM) {
  573. /* output resampled raw samples */
  574. fifo_write(&ost->fifo, buftmp, size_out,
  575. &ost->fifo.wptr);
  576. frame_bytes = enc->frame_size * 2 * enc->channels;
  577. while (fifo_read(&ost->fifo, audio_buf, frame_bytes,
  578. &ost->fifo.rptr) == 0) {
  579. ret = avcodec_encode_audio(enc,
  580. audio_out, sizeof(audio_out), (short *)audio_buf);
  581. s->format->write_packet(s, ost->index, audio_out, ret);
  582. }
  583. } else {
  584. /* XXX: handle endianness */
  585. s->format->write_packet(s, ost->index, buftmp, size_out);
  586. }
  587. }
  588. /* write a picture to a raw mux */
  589. static void write_picture(AVFormatContext *s, int index, AVPicture *picture, int w, int h)
  590. {
  591. UINT8 *buf, *src, *dest;
  592. int size, j, i;
  593. /* XXX: not efficient, should add test if we can take
  594. directly the AVPicture */
  595. size = (w * h) * 3 / 2;
  596. buf = malloc(size);
  597. dest = buf;
  598. for(i=0;i<3;i++) {
  599. if (i == 1) {
  600. w >>= 1;
  601. h >>= 1;
  602. }
  603. src = picture->data[i];
  604. for(j=0;j<h;j++) {
  605. memcpy(dest, src, w);
  606. dest += w;
  607. src += picture->linesize[i];
  608. }
  609. }
  610. s->format->write_packet(s, index, buf, size);
  611. free(buf);
  612. }
  613. static void do_video_out(AVFormatContext *s,
  614. AVOutputStream *ost,
  615. AVInputStream *ist,
  616. AVPicture *pict)
  617. {
  618. int n1, n2, nb, i, ret, frame_number;
  619. AVPicture *picture;
  620. UINT8 video_buffer[128*1024];
  621. AVCodecContext *enc;
  622. enc = &ost->st->codec;
  623. frame_number = ist->frame_number;
  624. /* first drop frame if needed */
  625. n1 = ((INT64)frame_number * enc->frame_rate) / ist->st->codec.frame_rate;
  626. n2 = (((INT64)frame_number + 1) * enc->frame_rate) / ist->st->codec.frame_rate;
  627. nb = n2 - n1;
  628. if (nb <= 0)
  629. return;
  630. if (ost->video_resample) {
  631. picture = &ost->pict_tmp;
  632. img_resample(ost->img_resample_ctx, picture, pict);
  633. } else {
  634. picture = pict;
  635. }
  636. /* duplicates frame if needed */
  637. /* XXX: pb because no interleaving */
  638. for(i=0;i<nb;i++) {
  639. if (enc->codec_id != CODEC_ID_RAWVIDEO) {
  640. /* handles sameq here. This is not correct because it may
  641. not be a global option */
  642. if (same_quality) {
  643. ost->st->codec.quality = ist->st->codec.quality;
  644. }
  645. ret = avcodec_encode_video(&ost->st->codec,
  646. video_buffer, sizeof(video_buffer),
  647. picture);
  648. s->format->write_packet(s, ost->index, video_buffer, ret);
  649. } else {
  650. write_picture(s, ost->index, picture, enc->width, enc->height);
  651. }
  652. }
  653. }
  654. //#define HEX_DUMP
  655. #ifdef HEX_DUMP
  656. static void hex_dump(UINT8 *buf, int size)
  657. {
  658. int len, i, j, c;
  659. for(i=0;i<size;i+=16) {
  660. len = size - i;
  661. if (len > 16)
  662. len = 16;
  663. printf("%08x ", i);
  664. for(j=0;j<16;j++) {
  665. if (j < len)
  666. printf(" %02x", buf[i+j]);
  667. else
  668. printf(" ");
  669. }
  670. printf(" ");
  671. for(j=0;j<len;j++) {
  672. c = buf[i+j];
  673. if (c < ' ' || c > '~')
  674. c = '.';
  675. printf("%c", c);
  676. }
  677. printf("\n");
  678. }
  679. }
  680. #endif
  681. /*
  682. * The following code is the main loop of the file converter
  683. */
  684. static int av_encode(AVFormatContext **output_files,
  685. int nb_output_files,
  686. AVFormatContext **input_files,
  687. int nb_input_files,
  688. AVStreamMap *stream_maps, int nb_stream_maps)
  689. {
  690. int ret, i, j, k, n, nb_istreams, nb_ostreams = 0;
  691. AVFormatContext *is, *os;
  692. AVCodecContext *codec, *icodec;
  693. AVOutputStream *ost, **ost_table = NULL;
  694. AVInputStream *ist, **ist_table = NULL;
  695. INT64 min_pts, start_time;
  696. AVInputFile file_table[nb_input_files];
  697. memset(file_table, 0, sizeof(file_table));
  698. /* input stream init */
  699. j = 0;
  700. for(i=0;i<nb_input_files;i++) {
  701. is = input_files[i];
  702. file_table[i].ist_index = j;
  703. j += is->nb_streams;
  704. }
  705. nb_istreams = j;
  706. ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
  707. if (!ist_table)
  708. return -ENOMEM;
  709. for(i=0;i<nb_istreams;i++) {
  710. ist = av_mallocz(sizeof(AVInputStream));
  711. if (!ist)
  712. goto fail;
  713. ist_table[i] = ist;
  714. }
  715. j = 0;
  716. for(i=0;i<nb_input_files;i++) {
  717. is = input_files[i];
  718. for(k=0;k<is->nb_streams;k++) {
  719. ist = ist_table[j++];
  720. ist->st = is->streams[k];
  721. ist->file_index = i;
  722. ist->index = k;
  723. ist->discard = 1; /* the stream is discarded by default
  724. (changed later) */
  725. }
  726. }
  727. /* output stream init */
  728. nb_ostreams = 0;
  729. for(i=0;i<nb_output_files;i++) {
  730. os = output_files[i];
  731. nb_ostreams += os->nb_streams;
  732. }
  733. if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
  734. fprintf(stderr, "Number of stream maps must match number of output streams\n");
  735. exit(1);
  736. }
  737. ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
  738. if (!ost_table)
  739. goto fail;
  740. for(i=0;i<nb_ostreams;i++) {
  741. ost = av_mallocz(sizeof(AVOutputStream));
  742. if (!ost)
  743. goto fail;
  744. ost_table[i] = ost;
  745. }
  746. n = 0;
  747. for(k=0;k<nb_output_files;k++) {
  748. os = output_files[k];
  749. for(i=0;i<os->nb_streams;i++) {
  750. int found;
  751. ost = ost_table[n++];
  752. ost->file_index = k;
  753. ost->index = i;
  754. ost->st = os->streams[i];
  755. if (nb_stream_maps > 0) {
  756. ost->source_index = file_table[stream_maps[n-1].file_index].ist_index +
  757. stream_maps[n-1].stream_index;
  758. } else {
  759. /* get corresponding input stream index : we select the first one with the right type */
  760. found = 0;
  761. for(j=0;j<nb_istreams;j++) {
  762. ist = ist_table[j];
  763. if (ist->discard &&
  764. ist->st->codec.codec_type == ost->st->codec.codec_type) {
  765. ost->source_index = j;
  766. found = 1;
  767. }
  768. }
  769. if (!found) {
  770. /* try again and reuse existing stream */
  771. for(j=0;j<nb_istreams;j++) {
  772. ist = ist_table[j];
  773. if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
  774. ost->source_index = j;
  775. found = 1;
  776. }
  777. }
  778. if (!found) {
  779. fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
  780. ost->file_index, ost->index);
  781. exit(1);
  782. }
  783. }
  784. }
  785. ist = ist_table[ost->source_index];
  786. ist->discard = 0;
  787. }
  788. }
  789. /* dump the stream mapping */
  790. fprintf(stderr, "Stream mapping:\n");
  791. for(i=0;i<nb_ostreams;i++) {
  792. ost = ost_table[i];
  793. fprintf(stderr, " Stream #%d.%d -> #%d.%d\n",
  794. ist_table[ost->source_index]->file_index,
  795. ist_table[ost->source_index]->index,
  796. ost->file_index,
  797. ost->index);
  798. }
  799. /* for each output stream, we compute the right encoding parameters */
  800. for(i=0;i<nb_ostreams;i++) {
  801. ost = ost_table[i];
  802. ist = ist_table[ost->source_index];
  803. codec = &ost->st->codec;
  804. icodec = &ist->st->codec;
  805. switch(codec->codec_type) {
  806. case CODEC_TYPE_AUDIO:
  807. /* check if same codec with same parameters. If so, no
  808. reencoding is needed */
  809. if (codec->codec_id == icodec->codec_id &&
  810. codec->bit_rate == icodec->bit_rate &&
  811. codec->sample_rate == icodec->sample_rate &&
  812. codec->channels == icodec->channels) {
  813. /* no reencoding */
  814. } else {
  815. if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
  816. goto fail;
  817. if (codec->channels == icodec->channels &&
  818. codec->sample_rate == icodec->sample_rate) {
  819. ost->audio_resample = 0;
  820. } else {
  821. ost->audio_resample = 1;
  822. ost->resample = audio_resample_init(codec->channels, icodec->channels,
  823. codec->sample_rate,
  824. icodec->sample_rate);
  825. }
  826. ist->decoding_needed = 1;
  827. ost->encoding_needed = 1;
  828. }
  829. break;
  830. case CODEC_TYPE_VIDEO:
  831. /* check if same codec with same parameters. If so, no
  832. reencoding is needed */
  833. if (codec->codec_id == icodec->codec_id &&
  834. codec->bit_rate == icodec->bit_rate &&
  835. codec->frame_rate == icodec->frame_rate &&
  836. codec->width == icodec->width &&
  837. codec->height == icodec->height) {
  838. /* no reencoding */
  839. } else {
  840. if (codec->width == icodec->width &&
  841. codec->height == icodec->height) {
  842. ost->video_resample = 0;
  843. } else {
  844. UINT8 *buf;
  845. ost->video_resample = 1;
  846. buf = malloc((codec->width * codec->height * 3) / 2);
  847. if (!buf)
  848. goto fail;
  849. ost->pict_tmp.data[0] = buf;
  850. ost->pict_tmp.data[1] = ost->pict_tmp.data[0] + (codec->width * codec->height);
  851. ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (codec->width * codec->height) / 4;
  852. ost->pict_tmp.linesize[0] = codec->width;
  853. ost->pict_tmp.linesize[1] = codec->width / 2;
  854. ost->pict_tmp.linesize[2] = codec->width / 2;
  855. ost->img_resample_ctx = img_resample_init(
  856. ost->st->codec.width, ost->st->codec.height,
  857. ist->st->codec.width, ist->st->codec.height);
  858. }
  859. ost->encoding_needed = 1;
  860. ist->decoding_needed = 1;
  861. }
  862. break;
  863. }
  864. }
  865. /* open each encoder */
  866. for(i=0;i<nb_ostreams;i++) {
  867. ost = ost_table[i];
  868. if (ost->encoding_needed) {
  869. AVCodec *codec;
  870. codec = avcodec_find_encoder(ost->st->codec.codec_id);
  871. if (!codec) {
  872. fprintf(stderr, "Unsupported codec for output stream #%d.%d\n",
  873. ost->file_index, ost->index);
  874. exit(1);
  875. }
  876. if (avcodec_open(&ost->st->codec, codec) < 0) {
  877. fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n",
  878. ost->file_index, ost->index);
  879. exit(1);
  880. }
  881. }
  882. }
  883. /* open each decoder */
  884. for(i=0;i<nb_istreams;i++) {
  885. ist = ist_table[i];
  886. if (ist->decoding_needed) {
  887. AVCodec *codec;
  888. codec = avcodec_find_decoder(ist->st->codec.codec_id);
  889. if (!codec) {
  890. fprintf(stderr, "Unsupported codec for input stream #%d.%d\n",
  891. ist->file_index, ist->index);
  892. exit(1);
  893. }
  894. if (avcodec_open(&ist->st->codec, codec) < 0) {
  895. fprintf(stderr, "Error while opening codec for input stream #%d.%d\n",
  896. ist->file_index, ist->index);
  897. exit(1);
  898. }
  899. }
  900. }
  901. /* init pts */
  902. for(i=0;i<nb_istreams;i++) {
  903. ist = ist_table[i];
  904. ist->pts = 0;
  905. ist->frame_number = 0;
  906. }
  907. /* compute buffer size max (should use a complete heuristic) */
  908. for(i=0;i<nb_input_files;i++) {
  909. file_table[i].buffer_size_max = 2048;
  910. }
  911. /* open files and write file headers */
  912. for(i=0;i<nb_output_files;i++) {
  913. os = output_files[i];
  914. os->format->write_header(os);
  915. }
  916. start_time = gettime();
  917. min_pts = 0;
  918. for(;;) {
  919. int file_index, ist_index;
  920. AVPacket pkt;
  921. UINT8 *ptr;
  922. int len;
  923. UINT8 *data_buf;
  924. int data_size, got_picture;
  925. AVPicture picture;
  926. short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
  927. /* select the input file with the smallest pts */
  928. redo:
  929. file_index = -1;
  930. min_pts = (1ULL << 63) - 1;
  931. for(i=0;i<nb_istreams;i++) {
  932. ist = ist_table[i];
  933. if (!ist->discard && !file_table[ist->file_index].eof_reached && ist->pts < min_pts) {
  934. min_pts = ist->pts;
  935. file_index = ist->file_index;
  936. }
  937. }
  938. /* if none, if is finished */
  939. if (file_index < 0)
  940. break;
  941. /* finish if recording time exhausted */
  942. if (recording_time > 0 && min_pts >= recording_time)
  943. break;
  944. /* read a packet from it and output it in the fifo */
  945. is = input_files[file_index];
  946. if (av_read_packet(is, &pkt) < 0) {
  947. file_table[file_index].eof_reached = 1;
  948. continue;
  949. }
  950. ist_index = file_table[file_index].ist_index + pkt.stream_index;
  951. ist = ist_table[ist_index];
  952. if (ist->discard) {
  953. continue;
  954. }
  955. #ifdef HEX_DUMP
  956. printf("stream #%d, size=%d:\n", pkt.stream_index, pkt.size);
  957. hex_dump(pkt.data, pkt.size);
  958. #endif
  959. // printf("read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
  960. len = pkt.size;
  961. ptr = pkt.data;
  962. while (len > 0) {
  963. /* decode the packet if needed */
  964. data_buf = NULL; /* fail safe */
  965. data_size = 0;
  966. if (ist->decoding_needed) {
  967. switch(ist->st->codec.codec_type) {
  968. case CODEC_TYPE_AUDIO:
  969. if (ist->st->codec.codec_id == CODEC_ID_PCM) {
  970. /* no need to call a codec */
  971. data_buf = ptr;
  972. data_size = len;
  973. ret = len;
  974. } else {
  975. ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
  976. ptr, len);
  977. if (ret < 0)
  978. goto fail_decode;
  979. if (data_size == 0) {
  980. /* no audio frame */
  981. ptr += ret;
  982. len -= ret;
  983. continue;
  984. }
  985. data_buf = (UINT8 *)samples;
  986. }
  987. break;
  988. case CODEC_TYPE_VIDEO:
  989. if (ist->st->codec.codec_id == CODEC_ID_RAWVIDEO) {
  990. int size;
  991. size = (ist->st->codec.width * ist->st->codec.height);
  992. picture.data[0] = ptr;
  993. picture.data[1] = picture.data[0] + size;
  994. picture.data[2] = picture.data[1] + size / 4;
  995. picture.linesize[0] = ist->st->codec.width;
  996. picture.linesize[1] = ist->st->codec.width / 2;
  997. picture.linesize[2] = ist->st->codec.width / 2;
  998. ret = len;
  999. } else {
  1000. data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
  1001. ret = avcodec_decode_video(&ist->st->codec,
  1002. &picture, &got_picture, ptr, len);
  1003. if (ret < 0) {
  1004. fail_decode:
  1005. fprintf(stderr, "Error while decoding stream #%d.%d\n",
  1006. ist->file_index, ist->index);
  1007. av_free_packet(&pkt);
  1008. goto redo;
  1009. }
  1010. if (!got_picture) {
  1011. /* no picture yet */
  1012. ptr += ret;
  1013. len -= ret;
  1014. continue;
  1015. }
  1016. }
  1017. break;
  1018. default:
  1019. goto fail_decode;
  1020. }
  1021. } else {
  1022. data_buf = ptr;
  1023. data_size = len;
  1024. ret = len;
  1025. }
  1026. /* update pts */
  1027. switch(ist->st->codec.codec_type) {
  1028. case CODEC_TYPE_AUDIO:
  1029. ist->pts = (INT64)1000000 * ist->sample_index / ist->st->codec.sample_rate;
  1030. ist->sample_index += data_size / (2 * ist->st->codec.channels);
  1031. break;
  1032. case CODEC_TYPE_VIDEO:
  1033. ist->frame_number++;
  1034. ist->pts = ((INT64)ist->frame_number * 1000000 * FRAME_RATE_BASE) /
  1035. ist->st->codec.frame_rate;
  1036. break;
  1037. }
  1038. ptr += ret;
  1039. len -= ret;
  1040. /* transcode raw format, encode packets and output them */
  1041. for(i=0;i<nb_ostreams;i++) {
  1042. ost = ost_table[i];
  1043. if (ost->source_index == ist_index) {
  1044. os = output_files[ost->file_index];
  1045. if (ost->encoding_needed) {
  1046. switch(ost->st->codec.codec_type) {
  1047. case CODEC_TYPE_AUDIO:
  1048. do_audio_out(os, ost, ist, data_buf, data_size);
  1049. break;
  1050. case CODEC_TYPE_VIDEO:
  1051. do_video_out(os, ost, ist, &picture);
  1052. break;
  1053. }
  1054. } else {
  1055. /* no reencoding needed : output the packet directly */
  1056. os->format->write_packet(os, ost->index, data_buf, data_size);
  1057. }
  1058. }
  1059. }
  1060. }
  1061. av_free_packet(&pkt);
  1062. /* dump report by using the first video and audio streams */
  1063. {
  1064. char buf[1024];
  1065. AVFormatContext *oc;
  1066. INT64 total_size, ti;
  1067. AVCodecContext *enc;
  1068. int frame_number, vid;
  1069. double bitrate, ti1;
  1070. static INT64 last_time;
  1071. if ((min_pts - last_time) >= 500000) {
  1072. last_time = min_pts;
  1073. oc = output_files[0];
  1074. total_size = url_ftell(&oc->pb);
  1075. buf[0] = '\0';
  1076. ti = (1ULL << 63) - 1;
  1077. vid = 0;
  1078. for(i=0;i<nb_ostreams;i++) {
  1079. ost = ost_table[i];
  1080. enc = &ost->st->codec;
  1081. ist = ist_table[ost->source_index];
  1082. if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
  1083. frame_number = ist->frame_number;
  1084. sprintf(buf + strlen(buf), "frame=%5d q=%2d ",
  1085. frame_number, enc->quality);
  1086. vid = 1;
  1087. }
  1088. /* compute min pts value */
  1089. if (!ist->discard && ist->pts < ti) {
  1090. ti = ist->pts;
  1091. }
  1092. }
  1093. ti1 = ti / 1000000.0;
  1094. if (ti1 < 0.1)
  1095. ti1 = 0.1;
  1096. bitrate = (double)(total_size * 8) / ti1 / 1000.0;
  1097. sprintf(buf + strlen(buf), "size=%8LdkB time=%0.1f bitrate=%6.1fkbits/s",
  1098. total_size / 1024, ti1, bitrate);
  1099. fprintf(stderr, "%s \r", buf);
  1100. fflush(stderr);
  1101. }
  1102. }
  1103. }
  1104. /* dump report by using the first video and audio streams */
  1105. {
  1106. char buf[1024];
  1107. AVFormatContext *oc;
  1108. INT64 total_size, ti;
  1109. AVCodecContext *enc;
  1110. int frame_number, vid;
  1111. double bitrate, ti1;
  1112. oc = output_files[0];
  1113. total_size = url_ftell(&oc->pb);
  1114. buf[0] = '\0';
  1115. ti = (1ULL << 63) - 1;
  1116. vid = 0;
  1117. for(i=0;i<nb_ostreams;i++) {
  1118. ost = ost_table[i];
  1119. enc = &ost->st->codec;
  1120. ist = ist_table[ost->source_index];
  1121. if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
  1122. frame_number = ist->frame_number;
  1123. sprintf(buf + strlen(buf), "frame=%5d q=%2d ",
  1124. frame_number, enc->quality);
  1125. vid = 1;
  1126. }
  1127. /* compute min pts value */
  1128. if (!ist->discard && ist->pts < ti) {
  1129. ti = ist->pts;
  1130. }
  1131. }
  1132. ti1 = ti / 1000000.0;
  1133. if (ti1 < 0.1)
  1134. ti1 = 0.1;
  1135. bitrate = (double)(total_size * 8) / ti1 / 1000.0;
  1136. sprintf(buf + strlen(buf), "size=%8LdkB time=%0.1f bitrate=%6.1fkbits/s",
  1137. total_size / 1024, ti1, bitrate);
  1138. fprintf(stderr, "%s \n", buf);
  1139. }
  1140. /* close each encoder */
  1141. for(i=0;i<nb_ostreams;i++) {
  1142. ost = ost_table[i];
  1143. if (ost->encoding_needed) {
  1144. avcodec_close(&ost->st->codec);
  1145. }
  1146. }
  1147. /* close each decoder */
  1148. for(i=0;i<nb_istreams;i++) {
  1149. ist = ist_table[i];
  1150. if (ist->decoding_needed) {
  1151. avcodec_close(&ist->st->codec);
  1152. }
  1153. }
  1154. /* write the trailer if needed and close file */
  1155. for(i=0;i<nb_output_files;i++) {
  1156. os = output_files[i];
  1157. os->format->write_trailer(os);
  1158. }
  1159. /* finished ! */
  1160. ret = 0;
  1161. fail1:
  1162. if (ist_table) {
  1163. for(i=0;i<nb_istreams;i++) {
  1164. ist = ist_table[i];
  1165. if (ist) {
  1166. free(ist);
  1167. }
  1168. }
  1169. free(ist_table);
  1170. }
  1171. if (ost_table) {
  1172. for(i=0;i<nb_ostreams;i++) {
  1173. ost = ost_table[i];
  1174. if (ost) {
  1175. if (ost->pict_tmp.data[0])
  1176. free(ost->pict_tmp.data[0]);
  1177. if (ost->video_resample)
  1178. img_resample_close(ost->img_resample_ctx);
  1179. if (ost->audio_resample)
  1180. audio_resample_close(ost->resample);
  1181. free(ost);
  1182. }
  1183. }
  1184. free(ost_table);
  1185. }
  1186. return ret;
  1187. fail:
  1188. ret = -ENOMEM;
  1189. goto fail1;
  1190. }
  1191. #if 0
  1192. int file_read(const char *filename)
  1193. {
  1194. URLContext *h;
  1195. unsigned char buffer[1024];
  1196. int len, i;
  1197. if (url_open(&h, filename, O_RDONLY) < 0) {
  1198. printf("could not open '%s'\n", filename);
  1199. return -1;
  1200. }
  1201. for(;;) {
  1202. len = url_read(h, buffer, sizeof(buffer));
  1203. if (len <= 0)
  1204. break;
  1205. for(i=0;i<len;i++) putchar(buffer[i]);
  1206. }
  1207. url_close(h);
  1208. return 0;
  1209. }
  1210. #endif
  1211. void show_licence(void)
  1212. {
  1213. printf(
  1214. "ffmpeg version " FFMPEG_VERSION "\n"
  1215. "Copyright (c) 2000,2001 Gerard Lantau\n"
  1216. "This program is free software; you can redistribute it and/or modify\n"
  1217. "it under the terms of the GNU General Public License as published by\n"
  1218. "the Free Software Foundation; either version 2 of the License, or\n"
  1219. "(at your option) any later version.\n"
  1220. "\n"
  1221. "This program is distributed in the hope that it will be useful,\n"
  1222. "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
  1223. "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
  1224. "GNU General Public License for more details.\n"
  1225. "\n"
  1226. "You should have received a copy of the GNU General Public License\n"
  1227. "along with this program; if not, write to the Free Software\n"
  1228. "Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n"
  1229. );
  1230. exit(1);
  1231. }
  1232. void opt_format(const char *arg)
  1233. {
  1234. AVFormat *f;
  1235. f = first_format;
  1236. while (f != NULL && strcmp(f->name, arg) != 0) f = f->next;
  1237. if (f == NULL) {
  1238. fprintf(stderr, "Invalid format: %s\n", arg);
  1239. exit(1);
  1240. }
  1241. file_format = f;
  1242. }
  1243. void opt_video_bitrate(const char *arg)
  1244. {
  1245. video_bit_rate = atoi(arg) * 1000;
  1246. }
  1247. void opt_frame_rate(const char *arg)
  1248. {
  1249. frame_rate = (int)(strtod(arg, 0) * FRAME_RATE_BASE);
  1250. }
  1251. void opt_frame_size(const char *arg)
  1252. {
  1253. parse_image_size(&frame_width, &frame_height, arg);
  1254. if (frame_width <= 0 || frame_height <= 0) {
  1255. fprintf(stderr, "Incorrect frame size\n");
  1256. exit(1);
  1257. }
  1258. if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
  1259. fprintf(stderr, "Frame size must be a multiple of 2\n");
  1260. exit(1);
  1261. }
  1262. }
  1263. void opt_gop_size(const char *arg)
  1264. {
  1265. gop_size = atoi(arg);
  1266. }
  1267. void opt_qscale(const char *arg)
  1268. {
  1269. video_qscale = atoi(arg);
  1270. if (video_qscale < 0 ||
  1271. video_qscale > 31) {
  1272. fprintf(stderr, "qscale must be >= 1 and <= 31\n");
  1273. exit(1);
  1274. }
  1275. }
  1276. void opt_audio_bitrate(const char *arg)
  1277. {
  1278. audio_bit_rate = atoi(arg) * 1000;
  1279. }
  1280. void opt_audio_rate(const char *arg)
  1281. {
  1282. audio_sample_rate = atoi(arg);
  1283. }
  1284. void opt_audio_channels(const char *arg)
  1285. {
  1286. audio_channels = atoi(arg);
  1287. }
  1288. void opt_video_device(const char *arg)
  1289. {
  1290. v4l_device = strdup(arg);
  1291. }
  1292. void opt_audio_device(const char *arg)
  1293. {
  1294. audio_device = strdup(arg);
  1295. }
  1296. void opt_audio_codec(const char *arg)
  1297. {
  1298. AVCodec *p;
  1299. p = first_avcodec;
  1300. while (p) {
  1301. if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
  1302. break;
  1303. p = p->next;
  1304. }
  1305. if (p == NULL) {
  1306. fprintf(stderr, "Unknown audio codec '%s'\n", arg);
  1307. exit(1);
  1308. } else {
  1309. audio_codec_id = p->id;
  1310. }
  1311. }
  1312. const char *motion_str[] = {
  1313. "zero",
  1314. "full",
  1315. "log",
  1316. "phods",
  1317. NULL,
  1318. };
  1319. void opt_motion_estimation(const char *arg)
  1320. {
  1321. const char **p;
  1322. p = motion_str;
  1323. for(;;) {
  1324. if (!*p) {
  1325. fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
  1326. exit(1);
  1327. }
  1328. if (!strcmp(*p, arg))
  1329. break;
  1330. p++;
  1331. }
  1332. motion_estimation_method = p - motion_str;
  1333. }
  1334. void opt_video_codec(const char *arg)
  1335. {
  1336. AVCodec *p;
  1337. p = first_avcodec;
  1338. while (p) {
  1339. if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
  1340. break;
  1341. p = p->next;
  1342. }
  1343. if (p == NULL) {
  1344. fprintf(stderr, "Unknown video codec '%s'\n", arg);
  1345. exit(1);
  1346. } else {
  1347. video_codec_id = p->id;
  1348. }
  1349. }
  1350. void opt_map(const char *arg)
  1351. {
  1352. AVStreamMap *m;
  1353. const char *p;
  1354. p = arg;
  1355. m = &stream_maps[nb_stream_maps++];
  1356. m->file_index = strtol(arg, (char **)&p, 0);
  1357. if (*p)
  1358. p++;
  1359. m->stream_index = strtol(arg, (char **)&p, 0);
  1360. }
  1361. void opt_recording_time(const char *arg)
  1362. {
  1363. recording_time = parse_date(arg, 1);
  1364. }
  1365. /* return the number of packet read to find the codec parameters */
  1366. int find_codec_parameters(AVFormatContext *ic)
  1367. {
  1368. int val, i, count, ret, got_picture, size;
  1369. AVCodec *codec;
  1370. AVCodecContext *enc;
  1371. AVStream *st;
  1372. AVPacket *pkt;
  1373. AVPicture picture;
  1374. AVPacketList *pktl, **ppktl;
  1375. short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
  1376. UINT8 *ptr;
  1377. count = 0;
  1378. ppktl = &ic->packet_buffer;
  1379. for(;;) {
  1380. for(i=0;i<ic->nb_streams;i++) {
  1381. enc = &ic->streams[i]->codec;
  1382. switch(enc->codec_type) {
  1383. case CODEC_TYPE_AUDIO:
  1384. val = enc->sample_rate;
  1385. break;
  1386. case CODEC_TYPE_VIDEO:
  1387. val = enc->width;
  1388. break;
  1389. default:
  1390. val = 1;
  1391. break;
  1392. }
  1393. /* if no parameters supplied, then we should read it from
  1394. the stream */
  1395. if (val == 0)
  1396. break;
  1397. }
  1398. if (i == ic->nb_streams) {
  1399. ret = count;
  1400. break;
  1401. }
  1402. if (count == 0) {
  1403. /* open each codec */
  1404. for(i=0;i<ic->nb_streams;i++) {
  1405. st = ic->streams[i];
  1406. codec = avcodec_find_decoder(st->codec.codec_id);
  1407. if (codec == NULL) {
  1408. ret = -1;
  1409. goto the_end;
  1410. }
  1411. avcodec_open(&st->codec, codec);
  1412. }
  1413. }
  1414. pktl = av_mallocz(sizeof(AVPacketList));
  1415. if (!pktl) {
  1416. ret = -1;
  1417. break;
  1418. }
  1419. /* add the packet in the buffered packet list */
  1420. *ppktl = pktl;
  1421. ppktl = &pktl->next;
  1422. pkt = &pktl->pkt;
  1423. if (ic->format->read_packet(ic, pkt) < 0) {
  1424. ret = -1;
  1425. break;
  1426. }
  1427. st = ic->streams[pkt->stream_index];
  1428. /* decode the data and update codec parameters */
  1429. ptr = pkt->data;
  1430. size = pkt->size;
  1431. while (size > 0) {
  1432. switch(st->codec.codec_type) {
  1433. case CODEC_TYPE_VIDEO:
  1434. ret = avcodec_decode_video(&st->codec, &picture, &got_picture, ptr, size);
  1435. break;
  1436. case CODEC_TYPE_AUDIO:
  1437. ret = avcodec_decode_audio(&st->codec, samples, &got_picture, ptr, size);
  1438. break;
  1439. default:
  1440. ret = -1;
  1441. break;
  1442. }
  1443. if (ret < 0) {
  1444. ret = -1;
  1445. goto the_end;
  1446. }
  1447. if (got_picture)
  1448. break;
  1449. ptr += ret;
  1450. size -= ret;
  1451. }
  1452. count++;
  1453. }
  1454. the_end:
  1455. if (count > 0) {
  1456. /* close each codec */
  1457. for(i=0;i<ic->nb_streams;i++) {
  1458. st = ic->streams[i];
  1459. avcodec_close(&st->codec);
  1460. }
  1461. }
  1462. return ret;
  1463. }
  1464. void opt_input_file(const char *filename)
  1465. {
  1466. AVFormatContext *ic;
  1467. AVFormatParameters params, *ap = &params;
  1468. URLFormat url_format;
  1469. AVFormat *fmt;
  1470. int err, i, ret;
  1471. ic = av_mallocz(sizeof(AVFormatContext));
  1472. strcpy(ic->filename, filename);
  1473. /* first format guess to know if we must open file */
  1474. fmt = file_format;
  1475. if (!fmt)
  1476. fmt = guess_format(NULL, filename, NULL);
  1477. if (fmt == NULL || !(fmt->flags & AVFMT_NOFILE)) {
  1478. /* open file */
  1479. if (url_fopen(&ic->pb, filename, URL_RDONLY) < 0) {
  1480. fprintf(stderr, "Could not open '%s'\n", filename);
  1481. exit(1);
  1482. }
  1483. /* find format and set default parameters */
  1484. fmt = file_format;
  1485. err = url_getformat(url_fileno(&ic->pb), &url_format);
  1486. if (err >= 0) {
  1487. if (!fmt)
  1488. fmt = guess_format(url_format.format_name, NULL, NULL);
  1489. ap->sample_rate = url_format.sample_rate;
  1490. ap->frame_rate = url_format.frame_rate;
  1491. ap->channels = url_format.channels;
  1492. ap->width = url_format.width;
  1493. ap->height = url_format.height;
  1494. ap->pix_fmt = url_format.pix_fmt;
  1495. } else {
  1496. if (!fmt)
  1497. fmt = guess_format(NULL, filename, NULL);
  1498. memset(ap, 0, sizeof(*ap));
  1499. }
  1500. } else {
  1501. memset(ap, 0, sizeof(*ap));
  1502. }
  1503. if (!fmt || !fmt->read_header) {
  1504. fprintf(stderr, "%s: Unknown file format\n", filename);
  1505. exit(1);
  1506. }
  1507. ic->format = fmt;
  1508. /* get default parameters from command line */
  1509. if (!ap->sample_rate)
  1510. ap->sample_rate = audio_sample_rate;
  1511. if (!ap->channels)
  1512. ap->channels = audio_channels;
  1513. if (!ap->frame_rate)
  1514. ap->frame_rate = frame_rate;
  1515. if (!ap->width)
  1516. ap->width = frame_width;
  1517. if (!ap->height)
  1518. ap->height = frame_height;
  1519. err = ic->format->read_header(ic, ap);
  1520. if (err < 0) {
  1521. fprintf(stderr, "%s: Error while parsing header\n", filename);
  1522. exit(1);
  1523. }
  1524. /* If not enough info for the codecs, we decode the first frames
  1525. to get it. (used in mpeg case for example) */
  1526. ret = find_codec_parameters(ic);
  1527. if (ret < 0) {
  1528. fprintf(stderr, "%s: could not find codec parameters\n", filename);
  1529. exit(1);
  1530. }
  1531. /* update the current parameters so that they match the one of the input stream */
  1532. for(i=0;i<ic->nb_streams;i++) {
  1533. AVCodecContext *enc = &ic->streams[i]->codec;
  1534. switch(enc->codec_type) {
  1535. case CODEC_TYPE_AUDIO:
  1536. audio_channels = enc->channels;
  1537. audio_sample_rate = enc->sample_rate;
  1538. break;
  1539. case CODEC_TYPE_VIDEO:
  1540. frame_height = enc->height;
  1541. frame_width = enc->width;
  1542. frame_rate = enc->frame_rate;
  1543. break;
  1544. }
  1545. }
  1546. input_files[nb_input_files] = ic;
  1547. /* dump the file content */
  1548. dump_format(ic, nb_input_files, filename, 0);
  1549. nb_input_files++;
  1550. file_format = NULL;
  1551. }
  1552. void opt_output_file(const char *filename)
  1553. {
  1554. AVStream *st;
  1555. AVFormatContext *oc;
  1556. int use_video, use_audio, nb_streams;
  1557. int codec_id;
  1558. if (!strcmp(filename, "-"))
  1559. filename = "pipe:";
  1560. oc = av_mallocz(sizeof(AVFormatContext));
  1561. if (!file_format) {
  1562. file_format = guess_format(NULL, filename, NULL);
  1563. if (!file_format)
  1564. file_format = &mpeg_mux_format;
  1565. }
  1566. oc->format = file_format;
  1567. if (!strcmp(file_format->name, "ffm") &&
  1568. strstart(filename, "http:", NULL)) {
  1569. /* special case for files sent to ffserver: we get the stream
  1570. parameters from ffserver */
  1571. if (read_ffserver_streams(oc, filename) < 0) {
  1572. fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
  1573. exit(1);
  1574. }
  1575. } else {
  1576. use_video = file_format->video_codec != CODEC_ID_NONE;
  1577. use_audio = file_format->audio_codec != CODEC_ID_NONE;
  1578. if (audio_disable) {
  1579. use_audio = 0;
  1580. }
  1581. if (video_disable) {
  1582. use_video = 0;
  1583. }
  1584. nb_streams = 0;
  1585. if (use_video) {
  1586. AVCodecContext *video_enc;
  1587. st = av_mallocz(sizeof(AVStream));
  1588. if (!st) {
  1589. fprintf(stderr, "Could not alloc stream\n");
  1590. exit(1);
  1591. }
  1592. video_enc = &st->codec;
  1593. codec_id = file_format->video_codec;
  1594. if (video_codec_id != CODEC_ID_NONE)
  1595. codec_id = video_codec_id;
  1596. video_enc->codec_id = codec_id;
  1597. video_enc->codec_type = CODEC_TYPE_VIDEO;
  1598. video_enc->bit_rate = video_bit_rate;
  1599. video_enc->frame_rate = frame_rate;
  1600. video_enc->width = frame_width;
  1601. video_enc->height = frame_height;
  1602. if (!intra_only)
  1603. video_enc->gop_size = gop_size;
  1604. else
  1605. video_enc->gop_size = 0;
  1606. if (video_qscale || same_quality) {
  1607. video_enc->flags |= CODEC_FLAG_QSCALE;
  1608. video_enc->quality = video_qscale;
  1609. }
  1610. oc->streams[nb_streams] = st;
  1611. nb_streams++;
  1612. }
  1613. if (use_audio) {
  1614. AVCodecContext *audio_enc;
  1615. st = av_mallocz(sizeof(AVStream));
  1616. if (!st) {
  1617. fprintf(stderr, "Could not alloc stream\n");
  1618. exit(1);
  1619. }
  1620. audio_enc = &st->codec;
  1621. codec_id = file_format->audio_codec;
  1622. if (audio_codec_id != CODEC_ID_NONE)
  1623. codec_id = audio_codec_id;
  1624. audio_enc->codec_id = codec_id;
  1625. audio_enc->codec_type = CODEC_TYPE_AUDIO;
  1626. audio_enc->bit_rate = audio_bit_rate;
  1627. audio_enc->sample_rate = audio_sample_rate;
  1628. audio_enc->channels = audio_channels;
  1629. oc->streams[nb_streams] = st;
  1630. nb_streams++;
  1631. }
  1632. oc->nb_streams = nb_streams;
  1633. if (!nb_streams) {
  1634. fprintf(stderr, "No audio or video selected\n");
  1635. exit(1);
  1636. }
  1637. if (str_title)
  1638. nstrcpy(oc->title, sizeof(oc->title), str_title);
  1639. if (str_author)
  1640. nstrcpy(oc->author, sizeof(oc->author), str_author);
  1641. if (str_copyright)
  1642. nstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
  1643. if (str_comment)
  1644. nstrcpy(oc->comment, sizeof(oc->comment), str_comment);
  1645. }
  1646. output_files[nb_output_files] = oc;
  1647. /* dump the file content */
  1648. dump_format(oc, nb_output_files, filename, 1);
  1649. nb_output_files++;
  1650. strcpy(oc->filename, filename);
  1651. if (!(oc->format->flags & AVFMT_NOFILE)) {
  1652. /* test if it already exists to avoid loosing precious files */
  1653. if (!file_overwrite &&
  1654. (strchr(filename, ':') == NULL ||
  1655. strstart(filename, "file:", NULL))) {
  1656. if (url_exist(filename)) {
  1657. int c;
  1658. printf("File '%s' already exists. Overwrite ? [y/N] ", filename);
  1659. fflush(stdout);
  1660. c = getchar();
  1661. if (toupper(c) != 'Y') {
  1662. fprintf(stderr, "Not overwriting - exiting\n");
  1663. exit(1);
  1664. }
  1665. }
  1666. }
  1667. /* open the file */
  1668. if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
  1669. fprintf(stderr, "Could not open '%s'\n", filename);
  1670. exit(1);
  1671. }
  1672. }
  1673. /* reset some options */
  1674. file_format = NULL;
  1675. audio_disable = 0;
  1676. video_disable = 0;
  1677. audio_codec_id = CODEC_ID_NONE;
  1678. video_codec_id = CODEC_ID_NONE;
  1679. }
  1680. void show_formats(void)
  1681. {
  1682. AVFormat *f;
  1683. URLProtocol *up;
  1684. AVCodec *p;
  1685. const char **pp;
  1686. printf("File formats:\n");
  1687. printf(" Encoding:");
  1688. for(f = first_format; f != NULL; f = f->next) {
  1689. if (f->write_header)
  1690. printf(" %s", f->name);
  1691. }
  1692. printf("\n");
  1693. printf(" Decoding:");
  1694. for(f = first_format; f != NULL; f = f->next) {
  1695. if (f->read_header)
  1696. printf(" %s", f->name);
  1697. }
  1698. printf("\n");
  1699. printf("Codecs:\n");
  1700. printf(" Encoders:");
  1701. for(p = first_avcodec; p != NULL; p = p->next) {
  1702. if (p->encode)
  1703. printf(" %s", p->name);
  1704. }
  1705. printf("\n");
  1706. printf(" Decoders:");
  1707. for(p = first_avcodec; p != NULL; p = p->next) {
  1708. if (p->decode)
  1709. printf(" %s", p->name);
  1710. }
  1711. printf("\n");
  1712. printf("Supported file protocols:");
  1713. for(up = first_protocol; up != NULL; up = up->next)
  1714. printf(" %s:", up->name);
  1715. printf("\n");
  1716. printf("Frame size abbreviations: sqcif qcif cif 4cif\n");
  1717. printf("Motion estimation methods:");
  1718. pp = motion_str;
  1719. while (*pp) {
  1720. printf(" %s", *pp);
  1721. if ((pp - motion_str) == ME_ZERO)
  1722. printf("(fastest)");
  1723. else if ((pp - motion_str) == ME_FULL)
  1724. printf("(slowest)");
  1725. else if ((pp - motion_str) == ME_LOG)
  1726. printf("(default)");
  1727. pp++;
  1728. }
  1729. printf("\n");
  1730. exit(1);
  1731. }
  1732. void show_help(void)
  1733. {
  1734. const OptionDef *po;
  1735. int i, expert;
  1736. printf("ffmpeg version " FFMPEG_VERSION ", Copyright (c) 2000,2001 Gerard Lantau\n"
  1737. "usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
  1738. "Hyper fast MPEG1/MPEG4/H263/RV and AC3/MPEG audio encoder\n"
  1739. "\n"
  1740. "Main options are:\n");
  1741. for(i=0;i<2;i++) {
  1742. if (i == 1)
  1743. printf("\nAdvanced options are:\n");
  1744. for(po = options; po->name != NULL; po++) {
  1745. char buf[64];
  1746. expert = (po->flags & OPT_EXPERT) != 0;
  1747. if (expert == i) {
  1748. strcpy(buf, po->name);
  1749. if (po->flags & HAS_ARG) {
  1750. strcat(buf, " ");
  1751. strcat(buf, po->argname);
  1752. }
  1753. printf("-%-17s %s\n", buf, po->help);
  1754. }
  1755. }
  1756. }
  1757. exit(1);
  1758. }
  1759. const OptionDef options[] = {
  1760. { "L", 0, {show_licence}, "show license" },
  1761. { "h", 0, {show_help}, "show help" },
  1762. { "formats", 0, {show_formats}, "show available formats, codecs, protocols, ..." },
  1763. { "f", HAS_ARG, {opt_format}, "force format", "fmt" },
  1764. { "i", HAS_ARG, {opt_input_file}, "input file name", "filename" },
  1765. { "y", OPT_BOOL, {int_arg:&file_overwrite}, "overwrite output files" },
  1766. { "map", HAS_ARG | OPT_EXPERT, {opt_map}, "set input stream mapping", "file:stream" },
  1767. { "t", HAS_ARG, {opt_recording_time}, "set the recording time", "duration" },
  1768. { "title", HAS_ARG | OPT_STRING, {str_arg: &str_title}, "set the title", "string" },
  1769. { "author", HAS_ARG | OPT_STRING, {str_arg: &str_author}, "set the author", "string" },
  1770. { "copyright", HAS_ARG | OPT_STRING, {str_arg: &str_copyright}, "set the copyright", "string" },
  1771. { "comment", HAS_ARG | OPT_STRING, {str_arg: &str_comment}, "set the comment", "string" },
  1772. /* video options */
  1773. { "b", HAS_ARG, {opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
  1774. { "r", HAS_ARG, {opt_frame_rate}, "set frame rate (in Hz)", "rate" },
  1775. { "s", HAS_ARG, {opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
  1776. { "g", HAS_ARG | OPT_EXPERT, {opt_gop_size}, "set the group of picture size", "gop_size" },
  1777. { "intra", OPT_BOOL | OPT_EXPERT, {int_arg: &intra_only}, "use only intra frames"},
  1778. { "vn", OPT_BOOL, {int_arg: &video_disable}, "disable video" },
  1779. { "qscale", HAS_ARG | OPT_EXPERT, {opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
  1780. { "vd", HAS_ARG | OPT_EXPERT, {opt_video_device}, "set video device", "device" },
  1781. { "vcodec", HAS_ARG | OPT_EXPERT, {opt_video_codec}, "force video codec", "codec" },
  1782. { "me", HAS_ARG | OPT_EXPERT, {opt_motion_estimation}, "set motion estimation method",
  1783. "method" },
  1784. { "sameq", OPT_BOOL, {int_arg: &same_quality},
  1785. "use same video quality as source (implies VBR)" },
  1786. /* audio options */
  1787. { "ab", HAS_ARG, {opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
  1788. { "ar", HAS_ARG, {opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
  1789. { "ac", HAS_ARG, {opt_audio_channels}, "set number of audio channels", "channels" },
  1790. { "an", OPT_BOOL, {int_arg: &audio_disable}, "disable audio" },
  1791. { "ad", HAS_ARG | OPT_EXPERT, {opt_audio_device}, "set audio device", "device" },
  1792. { "acodec", HAS_ARG | OPT_EXPERT, {opt_audio_codec}, "force audio codec", "codec" },
  1793. { NULL, },
  1794. };
  1795. int main(int argc, char **argv)
  1796. {
  1797. int optindex, i;
  1798. const char *opt, *arg;
  1799. const OptionDef *po;
  1800. register_all();
  1801. if (argc <= 1)
  1802. show_help();
  1803. optindex = 1;
  1804. while (optindex < argc) {
  1805. opt = argv[optindex++];
  1806. if (opt[0] == '-' && opt[1] != '\0') {
  1807. po = options;
  1808. while (po->name != NULL) {
  1809. if (!strcmp(opt + 1, po->name))
  1810. break;
  1811. po++;
  1812. }
  1813. if (!po->name) {
  1814. fprintf(stderr, "%s: unrecognized option '%s'\n", argv[0], opt);
  1815. exit(1);
  1816. }
  1817. arg = NULL;
  1818. if (po->flags & HAS_ARG)
  1819. arg = argv[optindex++];
  1820. if (po->flags & OPT_STRING) {
  1821. char *str;
  1822. str = strdup(arg);
  1823. *po->u.str_arg = str;
  1824. } else if (po->flags & OPT_BOOL) {
  1825. *po->u.int_arg = 1;
  1826. } else {
  1827. po->u.func_arg(arg);
  1828. }
  1829. } else {
  1830. opt_output_file(opt);
  1831. }
  1832. }
  1833. if (nb_input_files == 0) {
  1834. if (nb_output_files != 1) {
  1835. fprintf(stderr, "Only one output file supported when grabbing\n");
  1836. exit(1);
  1837. }
  1838. av_grab(output_files[0]);
  1839. } else {
  1840. if (nb_output_files <= 0) {
  1841. fprintf(stderr, "Must supply at least one output file\n");
  1842. exit(1);
  1843. }
  1844. av_encode(output_files, nb_output_files, input_files, nb_input_files,
  1845. stream_maps, nb_stream_maps);
  1846. }
  1847. /* close files */
  1848. for(i=0;i<nb_output_files;i++) {
  1849. if (!(output_files[i]->format->flags & AVFMT_NOFILE))
  1850. url_fclose(&output_files[i]->pb);
  1851. }
  1852. for(i=0;i<nb_input_files;i++) {
  1853. if (!(input_files[i]->format->flags & AVFMT_NOFILE))
  1854. url_fclose(&input_files[i]->pb);
  1855. }
  1856. return 0;
  1857. }