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.

2533 lines
80KB

  1. /*
  2. * FFmpeg main
  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. #define HAVE_AV_CONFIG_H
  20. #include "avformat.h"
  21. #include "tick.h"
  22. #ifndef CONFIG_WIN32
  23. #include <unistd.h>
  24. #include <fcntl.h>
  25. #include <sys/ioctl.h>
  26. #include <sys/time.h>
  27. #include <termios.h>
  28. #include <sys/resource.h>
  29. #endif
  30. #ifdef __BEOS__
  31. /* for snooze() */
  32. #include <OS.h>
  33. #endif
  34. #include <time.h>
  35. #include <ctype.h>
  36. #define MAXINT64 INT64_C(0x7fffffffffffffff)
  37. typedef struct {
  38. const char *name;
  39. int flags;
  40. #define HAS_ARG 0x0001
  41. #define OPT_BOOL 0x0002
  42. #define OPT_EXPERT 0x0004
  43. #define OPT_STRING 0x0008
  44. union {
  45. void (*func_arg)();
  46. int *int_arg;
  47. char **str_arg;
  48. } u;
  49. const char *help;
  50. const char *argname;
  51. } OptionDef;
  52. /* select an input stream for an output stream */
  53. typedef struct AVStreamMap {
  54. int file_index;
  55. int stream_index;
  56. } AVStreamMap;
  57. extern const OptionDef options[];
  58. void show_help(void);
  59. #define MAX_FILES 20
  60. static AVFormatContext *input_files[MAX_FILES];
  61. static int nb_input_files = 0;
  62. static AVFormatContext *output_files[MAX_FILES];
  63. static int nb_output_files = 0;
  64. static AVStreamMap stream_maps[MAX_FILES];
  65. static int nb_stream_maps;
  66. static AVInputFormat *file_iformat;
  67. static AVOutputFormat *file_oformat;
  68. static int frame_width = 160;
  69. static int frame_height = 128;
  70. static int frame_topBand = 0;
  71. static int frame_bottomBand = 0;
  72. static int frame_leftBand = 0;
  73. static int frame_rightBand = 0;
  74. static int frame_rate = 25 * FRAME_RATE_BASE;
  75. static int video_bit_rate = 200*1000;
  76. static int video_bit_rate_tolerance = 4000*1000;
  77. static int video_qscale = 0;
  78. static int video_qmin = 2;
  79. static int video_qmax = 31;
  80. static int video_qdiff = 3;
  81. static float video_qblur = 0.5;
  82. static float video_qcomp = 0.5;
  83. static float video_rc_qsquish=1.0;
  84. static float video_rc_qmod_amp=0;
  85. static int video_rc_qmod_freq=0;
  86. static char *video_rc_override_string=NULL;
  87. static char *video_rc_eq="tex^qComp";
  88. static int video_rc_buffer_size=0;
  89. static float video_rc_buffer_aggressivity=1.0;
  90. static int video_rc_max_rate=0;
  91. static int video_rc_min_rate=0;
  92. static float video_rc_initial_cplx=0;
  93. static float video_b_qfactor = 1.25;
  94. static float video_b_qoffset = 1.25;
  95. static float video_i_qfactor = -0.8;
  96. static float video_i_qoffset = 0.0;
  97. static int me_method = 0;
  98. static int video_disable = 0;
  99. static int video_codec_id = CODEC_ID_NONE;
  100. static int same_quality = 0;
  101. static int b_frames = 0;
  102. static int use_hq = 0;
  103. static int use_4mv = 0;
  104. static int do_deinterlace = 0;
  105. static int workaround_bugs = FF_BUG_AUTODETECT;
  106. static int error_resilience = 2;
  107. static int error_concealment = 3;
  108. static int dct_algo = 0;
  109. static int idct_algo = 0;
  110. static int use_part = 0;
  111. static int packet_size = 0;
  112. static int gop_size = 12;
  113. static int intra_only = 0;
  114. static int audio_sample_rate = 44100;
  115. static int audio_bit_rate = 64000;
  116. static int audio_disable = 0;
  117. static int audio_channels = 1;
  118. static int audio_codec_id = CODEC_ID_NONE;
  119. static INT64 recording_time = 0;
  120. static int file_overwrite = 0;
  121. static char *str_title = NULL;
  122. static char *str_author = NULL;
  123. static char *str_copyright = NULL;
  124. static char *str_comment = NULL;
  125. static int do_benchmark = 0;
  126. static int do_hex_dump = 0;
  127. static int do_play = 0;
  128. static int do_psnr = 0;
  129. static int do_vstats = 0;
  130. static int mpeg_vcd = 0;
  131. static int do_pass = 0;
  132. static char *pass_logfilename = NULL;
  133. static int audio_stream_copy = 0;
  134. static int video_stream_copy = 0;
  135. #define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
  136. #ifndef CONFIG_AUDIO_OSS
  137. const char *audio_device = "none";
  138. #endif
  139. #ifndef CONFIG_VIDEO4LINUX
  140. const char *v4l_device = "none";
  141. #endif
  142. typedef struct AVOutputStream {
  143. int file_index; /* file index */
  144. int index; /* stream index in the output file */
  145. int source_index; /* AVInputStream index */
  146. AVStream *st; /* stream in the output file */
  147. int encoding_needed; /* true if encoding needed for this stream */
  148. /* video only */
  149. AVPicture pict_tmp; /* temporary image for resizing */
  150. int video_resample;
  151. ImgReSampleContext *img_resample_ctx; /* for image resampling */
  152. /* audio only */
  153. int audio_resample;
  154. ReSampleContext *resample; /* for audio resampling */
  155. FifoBuffer fifo; /* for compression: one audio fifo per codec */
  156. FILE *logfile;
  157. } AVOutputStream;
  158. typedef struct AVInputStream {
  159. int file_index;
  160. int index;
  161. AVStream *st;
  162. int discard; /* true if stream data should be discarded */
  163. int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
  164. Ticker pts_ticker; /* Ticker for PTS calculation */
  165. int ticker_inited; /* to signal if the ticker was initialized */
  166. INT64 pts; /* current pts */
  167. int pts_increment; /* expected pts increment for next packet */
  168. int frame_number; /* current frame */
  169. INT64 sample_index; /* current sample */
  170. } AVInputStream;
  171. typedef struct AVInputFile {
  172. int eof_reached; /* true if eof reached */
  173. int ist_index; /* index of first stream in ist_table */
  174. int buffer_size; /* current total buffer size */
  175. int buffer_size_max; /* buffer size at which we consider we can stop
  176. buffering */
  177. int nb_streams; /* nb streams we are aware of */
  178. } AVInputFile;
  179. #ifndef CONFIG_WIN32
  180. /* init terminal so that we can grab keys */
  181. static struct termios oldtty;
  182. static void term_exit(void)
  183. {
  184. tcsetattr (0, TCSANOW, &oldtty);
  185. }
  186. static void term_init(void)
  187. {
  188. struct termios tty;
  189. tcgetattr (0, &tty);
  190. oldtty = tty;
  191. tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
  192. |INLCR|IGNCR|ICRNL|IXON);
  193. tty.c_oflag |= OPOST;
  194. tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
  195. tty.c_cflag &= ~(CSIZE|PARENB);
  196. tty.c_cflag |= CS8;
  197. tty.c_cc[VMIN] = 1;
  198. tty.c_cc[VTIME] = 0;
  199. tcsetattr (0, TCSANOW, &tty);
  200. atexit(term_exit);
  201. }
  202. /* read a key without blocking */
  203. static int read_key(void)
  204. {
  205. struct timeval tv;
  206. int n;
  207. unsigned char ch;
  208. fd_set rfds;
  209. FD_ZERO(&rfds);
  210. FD_SET(0, &rfds);
  211. tv.tv_sec = 0;
  212. tv.tv_usec = 0;
  213. n = select(1, &rfds, NULL, NULL, &tv);
  214. if (n > 0) {
  215. n = read(0, &ch, 1);
  216. if (n == 1)
  217. return ch;
  218. return n;
  219. }
  220. return -1;
  221. }
  222. #else
  223. /* no interactive support */
  224. static void term_exit(void)
  225. {
  226. }
  227. static void term_init(void)
  228. {
  229. }
  230. static int read_key(void)
  231. {
  232. return 0;
  233. }
  234. #endif
  235. int read_ffserver_streams(AVFormatContext *s, const char *filename)
  236. {
  237. int i, err;
  238. AVFormatContext *ic;
  239. err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
  240. if (err < 0)
  241. return err;
  242. /* copy stream format */
  243. s->nb_streams = ic->nb_streams;
  244. for(i=0;i<ic->nb_streams;i++) {
  245. AVStream *st;
  246. st = av_mallocz(sizeof(AVFormatContext));
  247. memcpy(st, ic->streams[i], sizeof(AVStream));
  248. s->streams[i] = st;
  249. }
  250. av_close_input_file(ic);
  251. return 0;
  252. }
  253. #define MAX_AUDIO_PACKET_SIZE 16384
  254. static void do_audio_out(AVFormatContext *s,
  255. AVOutputStream *ost,
  256. AVInputStream *ist,
  257. unsigned char *buf, int size)
  258. {
  259. UINT8 *buftmp;
  260. UINT8 audio_buf[2*MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it */
  261. UINT8 audio_out[MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it */
  262. int size_out, frame_bytes, ret;
  263. AVCodecContext *enc;
  264. enc = &ost->st->codec;
  265. if (ost->audio_resample) {
  266. buftmp = audio_buf;
  267. size_out = audio_resample(ost->resample,
  268. (short *)buftmp, (short *)buf,
  269. size / (ist->st->codec.channels * 2));
  270. size_out = size_out * enc->channels * 2;
  271. } else {
  272. buftmp = buf;
  273. size_out = size;
  274. }
  275. /* now encode as many frames as possible */
  276. if (enc->frame_size > 1) {
  277. /* output resampled raw samples */
  278. fifo_write(&ost->fifo, buftmp, size_out,
  279. &ost->fifo.wptr);
  280. frame_bytes = enc->frame_size * 2 * enc->channels;
  281. while (fifo_read(&ost->fifo, audio_buf, frame_bytes,
  282. &ost->fifo.rptr) == 0) {
  283. ret = avcodec_encode_audio(enc, audio_out, sizeof(audio_out),
  284. (short *)audio_buf);
  285. s->oformat->write_packet(s, ost->index, audio_out, ret, 0);
  286. }
  287. } else {
  288. /* output a pcm frame */
  289. /* XXX: change encoding codec API to avoid this ? */
  290. switch(enc->codec->id) {
  291. case CODEC_ID_PCM_S16LE:
  292. case CODEC_ID_PCM_S16BE:
  293. case CODEC_ID_PCM_U16LE:
  294. case CODEC_ID_PCM_U16BE:
  295. break;
  296. default:
  297. size_out = size_out >> 1;
  298. break;
  299. }
  300. ret = avcodec_encode_audio(enc, audio_out, size_out,
  301. (short *)buftmp);
  302. s->oformat->write_packet(s, ost->index, audio_out, ret, 0);
  303. }
  304. }
  305. /* write a picture to a raw mux */
  306. static void write_picture(AVFormatContext *s, int index, AVPicture *picture,
  307. int pix_fmt, int w, int h)
  308. {
  309. UINT8 *buf, *src, *dest;
  310. int size, j, i;
  311. /* XXX: not efficient, should add test if we can take
  312. directly the AVPicture */
  313. switch(pix_fmt) {
  314. case PIX_FMT_YUV420P:
  315. size = avpicture_get_size(pix_fmt, w, h);
  316. buf = av_malloc(size);
  317. if (!buf)
  318. return;
  319. dest = buf;
  320. for(i=0;i<3;i++) {
  321. if (i == 1) {
  322. w >>= 1;
  323. h >>= 1;
  324. }
  325. src = picture->data[i];
  326. for(j=0;j<h;j++) {
  327. memcpy(dest, src, w);
  328. dest += w;
  329. src += picture->linesize[i];
  330. }
  331. }
  332. break;
  333. case PIX_FMT_YUV422P:
  334. size = (w * h) * 2;
  335. buf = av_malloc(size);
  336. if (!buf)
  337. return;
  338. dest = buf;
  339. for(i=0;i<3;i++) {
  340. if (i == 1) {
  341. w >>= 1;
  342. }
  343. src = picture->data[i];
  344. for(j=0;j<h;j++) {
  345. memcpy(dest, src, w);
  346. dest += w;
  347. src += picture->linesize[i];
  348. }
  349. }
  350. break;
  351. case PIX_FMT_YUV444P:
  352. size = (w * h) * 3;
  353. buf = av_malloc(size);
  354. if (!buf)
  355. return;
  356. dest = buf;
  357. for(i=0;i<3;i++) {
  358. src = picture->data[i];
  359. for(j=0;j<h;j++) {
  360. memcpy(dest, src, w);
  361. dest += w;
  362. src += picture->linesize[i];
  363. }
  364. }
  365. break;
  366. case PIX_FMT_YUV422:
  367. size = (w * h) * 2;
  368. buf = av_malloc(size);
  369. if (!buf)
  370. return;
  371. dest = buf;
  372. src = picture->data[0];
  373. for(j=0;j<h;j++) {
  374. memcpy(dest, src, w * 2);
  375. dest += w * 2;
  376. src += picture->linesize[0];
  377. }
  378. break;
  379. case PIX_FMT_RGB24:
  380. case PIX_FMT_BGR24:
  381. size = (w * h) * 3;
  382. buf = av_malloc(size);
  383. if (!buf)
  384. return;
  385. dest = buf;
  386. src = picture->data[0];
  387. for(j=0;j<h;j++) {
  388. memcpy(dest, src, w * 3);
  389. dest += w * 3;
  390. src += picture->linesize[0];
  391. }
  392. break;
  393. default:
  394. return;
  395. }
  396. s->oformat->write_packet(s, index, buf, size, 0);
  397. av_free(buf);
  398. }
  399. static void do_video_out(AVFormatContext *s,
  400. AVOutputStream *ost,
  401. AVInputStream *ist,
  402. AVPicture *picture1,
  403. int *frame_size)
  404. {
  405. int n1, n2, nb, i, ret, frame_number, dec_frame_rate;
  406. AVPicture *picture, *picture2, *pict;
  407. AVPicture picture_tmp1, picture_tmp2;
  408. static UINT8 *video_buffer;
  409. UINT8 *buf = NULL, *buf1 = NULL;
  410. AVCodecContext *enc, *dec;
  411. #define VIDEO_BUFFER_SIZE (1024*1024)
  412. enc = &ost->st->codec;
  413. dec = &ist->st->codec;
  414. frame_number = ist->frame_number;
  415. dec_frame_rate = ist->st->r_frame_rate;
  416. // fprintf(stderr, "\n%d", dec_frame_rate);
  417. /* first drop frame if needed */
  418. n1 = ((INT64)frame_number * enc->frame_rate) / dec_frame_rate;
  419. n2 = (((INT64)frame_number + 1) * enc->frame_rate) / dec_frame_rate;
  420. nb = n2 - n1;
  421. if (nb <= 0)
  422. return;
  423. if (!video_buffer)
  424. video_buffer= av_malloc(VIDEO_BUFFER_SIZE);
  425. if(!video_buffer) return;
  426. /* deinterlace : must be done before any resize */
  427. if (do_deinterlace) {
  428. int size;
  429. /* create temporary picture */
  430. size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
  431. buf1 = av_malloc(size);
  432. if (!buf1)
  433. return;
  434. picture2 = &picture_tmp2;
  435. avpicture_fill(picture2, buf1, dec->pix_fmt, dec->width, dec->height);
  436. if (avpicture_deinterlace(picture2, picture1,
  437. dec->pix_fmt, dec->width, dec->height) < 0) {
  438. /* if error, do not deinterlace */
  439. av_free(buf1);
  440. buf1 = NULL;
  441. picture2 = picture1;
  442. }
  443. } else {
  444. picture2 = picture1;
  445. }
  446. /* convert pixel format if needed */
  447. if (enc->pix_fmt != dec->pix_fmt) {
  448. int size;
  449. /* create temporary picture */
  450. size = avpicture_get_size(enc->pix_fmt, dec->width, dec->height);
  451. buf = av_malloc(size);
  452. if (!buf)
  453. return;
  454. pict = &picture_tmp1;
  455. avpicture_fill(pict, buf, enc->pix_fmt, dec->width, dec->height);
  456. if (img_convert(pict, enc->pix_fmt,
  457. picture2, dec->pix_fmt,
  458. dec->width, dec->height) < 0) {
  459. fprintf(stderr, "pixel format conversion not handled\n");
  460. goto the_end;
  461. }
  462. } else {
  463. pict = picture2;
  464. }
  465. /* XXX: resampling could be done before raw format convertion in
  466. some cases to go faster */
  467. /* XXX: only works for YUV420P */
  468. if (ost->video_resample) {
  469. picture = &ost->pict_tmp;
  470. img_resample(ost->img_resample_ctx, picture, pict);
  471. } else {
  472. picture = pict;
  473. }
  474. nb=1;
  475. /* duplicates frame if needed */
  476. /* XXX: pb because no interleaving */
  477. for(i=0;i<nb;i++) {
  478. if (enc->codec_id != CODEC_ID_RAWVIDEO) {
  479. /* handles sameq here. This is not correct because it may
  480. not be a global option */
  481. if (same_quality) {
  482. enc->quality = dec->quality;
  483. }
  484. ret = avcodec_encode_video(enc,
  485. video_buffer, VIDEO_BUFFER_SIZE,
  486. picture);
  487. //enc->frame_number = enc->real_pict_num;
  488. s->oformat->write_packet(s, ost->index, video_buffer, ret, 0);
  489. *frame_size = ret;
  490. //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
  491. // enc->frame_number-1, enc->real_pict_num, ret,
  492. // enc->pict_type);
  493. /* if two pass, output log */
  494. if (ost->logfile && enc->stats_out) {
  495. fprintf(ost->logfile, "%s", enc->stats_out);
  496. }
  497. } else {
  498. if (s->oformat->flags & AVFMT_RAWPICTURE) {
  499. /* raw pictures are written as AVPicture structure to
  500. avoid any copies. We support temorarily the older
  501. method. */
  502. s->oformat->write_packet(s, ost->index,
  503. (UINT8 *)picture, sizeof(AVPicture), 0);
  504. } else {
  505. write_picture(s, ost->index, picture, enc->pix_fmt, enc->width, enc->height);
  506. }
  507. }
  508. }
  509. the_end:
  510. av_free(buf);
  511. av_free(buf1);
  512. }
  513. static void do_video_stats(AVOutputStream *ost,
  514. AVInputStream *ist,
  515. int frame_size)
  516. {
  517. static FILE *fvstats=NULL;
  518. static INT64 total_size = 0;
  519. char filename[40];
  520. time_t today2;
  521. struct tm *today;
  522. AVCodecContext *enc;
  523. int frame_number;
  524. INT64 ti;
  525. double ti1, bitrate, avg_bitrate;
  526. if (!fvstats) {
  527. today2 = time(NULL);
  528. today = localtime(&today2);
  529. sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
  530. today->tm_min,
  531. today->tm_sec);
  532. fvstats = fopen(filename,"w");
  533. if (!fvstats) {
  534. perror("fopen");
  535. exit(1);
  536. }
  537. }
  538. ti = MAXINT64;
  539. enc = &ost->st->codec;
  540. total_size += frame_size;
  541. if (enc->codec_type == CODEC_TYPE_VIDEO) {
  542. frame_number = ist->frame_number;
  543. fprintf(fvstats, "frame= %5d q= %2d ", frame_number, enc->quality);
  544. if (do_psnr)
  545. fprintf(fvstats, "PSNR= %6.2f ", enc->psnr_y);
  546. fprintf(fvstats,"f_size= %6d ", frame_size);
  547. /* compute min pts value */
  548. if (!ist->discard && ist->pts < ti) {
  549. ti = ist->pts;
  550. }
  551. ti1 = (double)ti / 1000000.0;
  552. if (ti1 < 0.01)
  553. ti1 = 0.01;
  554. bitrate = (double)(frame_size * 8) * enc->frame_rate / FRAME_RATE_BASE / 1000.0;
  555. avg_bitrate = (double)(total_size * 8) / ti1 / 1000.0;
  556. fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
  557. (double)total_size / 1024, ti1, bitrate, avg_bitrate);
  558. fprintf(fvstats,"type= %s\n", enc->key_frame == 1 ? "I" : "P");
  559. }
  560. }
  561. /*
  562. * The following code is the main loop of the file converter
  563. */
  564. static int av_encode(AVFormatContext **output_files,
  565. int nb_output_files,
  566. AVFormatContext **input_files,
  567. int nb_input_files,
  568. AVStreamMap *stream_maps, int nb_stream_maps)
  569. {
  570. int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
  571. AVFormatContext *is, *os;
  572. AVCodecContext *codec, *icodec;
  573. AVOutputStream *ost, **ost_table = NULL;
  574. AVInputStream *ist, **ist_table = NULL;
  575. INT64 min_pts, start_time;
  576. AVInputFile *file_table;
  577. AVFormatContext *stream_no_data;
  578. int key;
  579. file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
  580. if (!file_table)
  581. goto fail;
  582. /* input stream init */
  583. j = 0;
  584. for(i=0;i<nb_input_files;i++) {
  585. is = input_files[i];
  586. file_table[i].ist_index = j;
  587. file_table[i].nb_streams = is->nb_streams;
  588. j += is->nb_streams;
  589. }
  590. nb_istreams = j;
  591. ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
  592. if (!ist_table)
  593. goto fail;
  594. for(i=0;i<nb_istreams;i++) {
  595. ist = av_mallocz(sizeof(AVInputStream));
  596. if (!ist)
  597. goto fail;
  598. ist_table[i] = ist;
  599. }
  600. j = 0;
  601. for(i=0;i<nb_input_files;i++) {
  602. is = input_files[i];
  603. for(k=0;k<is->nb_streams;k++) {
  604. ist = ist_table[j++];
  605. ist->st = is->streams[k];
  606. ist->file_index = i;
  607. ist->index = k;
  608. ist->discard = 1; /* the stream is discarded by default
  609. (changed later) */
  610. }
  611. }
  612. /* output stream init */
  613. nb_ostreams = 0;
  614. for(i=0;i<nb_output_files;i++) {
  615. os = output_files[i];
  616. nb_ostreams += os->nb_streams;
  617. if (mpeg_vcd)
  618. os->flags |= AVF_FLAG_VCD;
  619. }
  620. if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
  621. fprintf(stderr, "Number of stream maps must match number of output streams\n");
  622. exit(1);
  623. }
  624. ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
  625. if (!ost_table)
  626. goto fail;
  627. for(i=0;i<nb_ostreams;i++) {
  628. ost = av_mallocz(sizeof(AVOutputStream));
  629. if (!ost)
  630. goto fail;
  631. ost_table[i] = ost;
  632. }
  633. n = 0;
  634. for(k=0;k<nb_output_files;k++) {
  635. os = output_files[k];
  636. for(i=0;i<os->nb_streams;i++) {
  637. int found;
  638. ost = ost_table[n++];
  639. ost->file_index = k;
  640. ost->index = i;
  641. ost->st = os->streams[i];
  642. if (nb_stream_maps > 0) {
  643. ost->source_index = file_table[stream_maps[n-1].file_index].ist_index +
  644. stream_maps[n-1].stream_index;
  645. } else {
  646. /* get corresponding input stream index : we select the first one with the right type */
  647. found = 0;
  648. for(j=0;j<nb_istreams;j++) {
  649. ist = ist_table[j];
  650. if (ist->discard &&
  651. ist->st->codec.codec_type == ost->st->codec.codec_type) {
  652. ost->source_index = j;
  653. found = 1;
  654. }
  655. }
  656. if (!found) {
  657. /* try again and reuse existing stream */
  658. for(j=0;j<nb_istreams;j++) {
  659. ist = ist_table[j];
  660. if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
  661. ost->source_index = j;
  662. found = 1;
  663. }
  664. }
  665. if (!found) {
  666. fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
  667. ost->file_index, ost->index);
  668. exit(1);
  669. }
  670. }
  671. }
  672. ist = ist_table[ost->source_index];
  673. ist->discard = 0;
  674. }
  675. }
  676. /* for each output stream, we compute the right encoding parameters */
  677. for(i=0;i<nb_ostreams;i++) {
  678. ost = ost_table[i];
  679. ist = ist_table[ost->source_index];
  680. codec = &ost->st->codec;
  681. icodec = &ist->st->codec;
  682. if (ost->st->stream_copy) {
  683. /* if stream_copy is selected, no need to decode or encode */
  684. codec->codec_id = icodec->codec_id;
  685. codec->codec_type = icodec->codec_type;
  686. codec->codec_tag = icodec->codec_tag;
  687. codec->bit_rate = icodec->bit_rate;
  688. switch(codec->codec_type) {
  689. case CODEC_TYPE_AUDIO:
  690. codec->sample_rate = icodec->sample_rate;
  691. codec->channels = icodec->channels;
  692. break;
  693. case CODEC_TYPE_VIDEO:
  694. codec->frame_rate = icodec->frame_rate;
  695. codec->width = icodec->width;
  696. codec->height = icodec->height;
  697. break;
  698. default:
  699. av_abort();
  700. }
  701. } else {
  702. switch(codec->codec_type) {
  703. case CODEC_TYPE_AUDIO:
  704. if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
  705. goto fail;
  706. if (codec->channels == icodec->channels &&
  707. codec->sample_rate == icodec->sample_rate) {
  708. ost->audio_resample = 0;
  709. } else {
  710. if (codec->channels != icodec->channels &&
  711. icodec->codec_id == CODEC_ID_AC3) {
  712. /* Special case for 5:1 AC3 input */
  713. /* and mono or stereo output */
  714. /* Request specific number of channels */
  715. icodec->channels = codec->channels;
  716. if (codec->sample_rate == icodec->sample_rate)
  717. ost->audio_resample = 0;
  718. else {
  719. ost->audio_resample = 1;
  720. ost->resample = audio_resample_init(codec->channels, icodec->channels,
  721. codec->sample_rate,
  722. icodec->sample_rate);
  723. }
  724. /* Request specific number of channels */
  725. icodec->channels = codec->channels;
  726. } else {
  727. ost->audio_resample = 1;
  728. ost->resample = audio_resample_init(codec->channels, icodec->channels,
  729. codec->sample_rate,
  730. icodec->sample_rate);
  731. }
  732. }
  733. ist->decoding_needed = 1;
  734. ost->encoding_needed = 1;
  735. break;
  736. case CODEC_TYPE_VIDEO:
  737. if (codec->width == icodec->width &&
  738. codec->height == icodec->height) {
  739. ost->video_resample = 0;
  740. } else {
  741. UINT8 *buf;
  742. ost->video_resample = 1;
  743. buf = av_malloc((codec->width * codec->height * 3) / 2);
  744. if (!buf)
  745. goto fail;
  746. ost->pict_tmp.data[0] = buf;
  747. ost->pict_tmp.data[1] = ost->pict_tmp.data[0] + (codec->width * codec->height);
  748. ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (codec->width * codec->height) / 4;
  749. ost->pict_tmp.linesize[0] = codec->width;
  750. ost->pict_tmp.linesize[1] = codec->width / 2;
  751. ost->pict_tmp.linesize[2] = codec->width / 2;
  752. ost->img_resample_ctx = img_resample_full_init(
  753. ost->st->codec.width, ost->st->codec.height,
  754. ist->st->codec.width, ist->st->codec.height,
  755. frame_topBand, frame_bottomBand,
  756. frame_leftBand, frame_rightBand);
  757. }
  758. ost->encoding_needed = 1;
  759. ist->decoding_needed = 1;
  760. break;
  761. default:
  762. av_abort();
  763. }
  764. /* two pass mode */
  765. if (ost->encoding_needed &&
  766. (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
  767. char logfilename[1024];
  768. FILE *f;
  769. int size;
  770. char *logbuffer;
  771. snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
  772. pass_logfilename ?
  773. pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
  774. if (codec->flags & CODEC_FLAG_PASS1) {
  775. f = fopen(logfilename, "w");
  776. if (!f) {
  777. perror(logfilename);
  778. exit(1);
  779. }
  780. ost->logfile = f;
  781. } else {
  782. /* read the log file */
  783. f = fopen(logfilename, "r");
  784. if (!f) {
  785. perror(logfilename);
  786. exit(1);
  787. }
  788. fseek(f, 0, SEEK_END);
  789. size = ftell(f);
  790. fseek(f, 0, SEEK_SET);
  791. logbuffer = av_malloc(size + 1);
  792. if (!logbuffer) {
  793. fprintf(stderr, "Could not allocate log buffer\n");
  794. exit(1);
  795. }
  796. fread(logbuffer, 1, size, f);
  797. fclose(f);
  798. logbuffer[size] = '\0';
  799. codec->stats_in = logbuffer;
  800. }
  801. }
  802. }
  803. }
  804. /* dump the file output parameters - cannot be done before in case
  805. of stream copy */
  806. for(i=0;i<nb_output_files;i++) {
  807. dump_format(output_files[i], i, output_files[i]->filename, 1);
  808. }
  809. /* dump the stream mapping */
  810. fprintf(stderr, "Stream mapping:\n");
  811. for(i=0;i<nb_ostreams;i++) {
  812. ost = ost_table[i];
  813. fprintf(stderr, " Stream #%d.%d -> #%d.%d\n",
  814. ist_table[ost->source_index]->file_index,
  815. ist_table[ost->source_index]->index,
  816. ost->file_index,
  817. ost->index);
  818. }
  819. /* open each encoder */
  820. for(i=0;i<nb_ostreams;i++) {
  821. ost = ost_table[i];
  822. if (ost->encoding_needed) {
  823. AVCodec *codec;
  824. codec = avcodec_find_encoder(ost->st->codec.codec_id);
  825. if (!codec) {
  826. fprintf(stderr, "Unsupported codec for output stream #%d.%d\n",
  827. ost->file_index, ost->index);
  828. exit(1);
  829. }
  830. if (avcodec_open(&ost->st->codec, codec) < 0) {
  831. fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n",
  832. ost->file_index, ost->index);
  833. exit(1);
  834. }
  835. }
  836. }
  837. /* open each decoder */
  838. for(i=0;i<nb_istreams;i++) {
  839. ist = ist_table[i];
  840. if (ist->decoding_needed) {
  841. AVCodec *codec;
  842. codec = avcodec_find_decoder(ist->st->codec.codec_id);
  843. if (!codec) {
  844. fprintf(stderr, "Unsupported codec for input stream #%d.%d\n",
  845. ist->file_index, ist->index);
  846. exit(1);
  847. }
  848. if (avcodec_open(&ist->st->codec, codec) < 0) {
  849. fprintf(stderr, "Error while opening codec for input stream #%d.%d\n",
  850. ist->file_index, ist->index);
  851. exit(1);
  852. }
  853. //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
  854. // ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
  855. }
  856. }
  857. /* init pts */
  858. for(i=0;i<nb_istreams;i++) {
  859. ist = ist_table[i];
  860. ist->pts = 0;
  861. ist->frame_number = 0;
  862. }
  863. /* compute buffer size max (should use a complete heuristic) */
  864. for(i=0;i<nb_input_files;i++) {
  865. file_table[i].buffer_size_max = 2048;
  866. }
  867. /* open files and write file headers */
  868. for(i=0;i<nb_output_files;i++) {
  869. os = output_files[i];
  870. if (av_write_header(os) < 0) {
  871. fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
  872. ret = -EINVAL;
  873. goto fail;
  874. }
  875. }
  876. #ifndef CONFIG_WIN32
  877. if (!do_play) {
  878. fprintf(stderr, "Press [q] to stop encoding\n");
  879. } else {
  880. fprintf(stderr, "Press [q] to stop playing\n");
  881. }
  882. #endif
  883. term_init();
  884. start_time = av_gettime();
  885. min_pts = 0;
  886. stream_no_data = 0;
  887. key = -1;
  888. for(;;) {
  889. int file_index, ist_index;
  890. AVPacket pkt;
  891. UINT8 *ptr;
  892. int len;
  893. UINT8 *data_buf;
  894. int data_size, got_picture;
  895. AVPicture picture;
  896. short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
  897. redo:
  898. /* if 'q' pressed, exits */
  899. if (key) {
  900. /* read_key() returns 0 on EOF */
  901. key = read_key();
  902. if (key == 'q')
  903. break;
  904. }
  905. /* select the input file with the smallest pts */
  906. file_index = -1;
  907. min_pts = MAXINT64;
  908. for(i=0;i<nb_istreams;i++) {
  909. ist = ist_table[i];
  910. /* For some reason, the pts_increment code breaks q estimation?!? */
  911. if (!ist->discard && !file_table[ist->file_index].eof_reached &&
  912. ist->pts /* + ist->pts_increment */ < min_pts && input_files[ist->file_index] != stream_no_data) {
  913. min_pts = ist->pts /* + ist->pts_increment */;
  914. file_index = ist->file_index;
  915. }
  916. }
  917. /* if none, if is finished */
  918. if (file_index < 0) {
  919. if (stream_no_data) {
  920. #ifndef CONFIG_WIN32 /* no usleep in VisualC ? */
  921. #ifdef __BEOS__
  922. snooze(10 * 1000); /* mmu_man */ /* in microsec */
  923. #elif defined(__CYGWIN__)
  924. usleep(10 * 1000);
  925. #else
  926. struct timespec ts;
  927. ts.tv_sec = 0;
  928. ts.tv_nsec = 1000 * 1000 * 10;
  929. nanosleep(&ts, 0);
  930. #endif
  931. #endif
  932. stream_no_data = 0;
  933. continue;
  934. }
  935. break;
  936. }
  937. /* finish if recording time exhausted */
  938. if (recording_time > 0 && min_pts >= recording_time)
  939. break;
  940. /* read a packet from it and output it in the fifo */
  941. is = input_files[file_index];
  942. if (av_read_packet(is, &pkt) < 0) {
  943. file_table[file_index].eof_reached = 1;
  944. continue;
  945. }
  946. if (!pkt.size) {
  947. stream_no_data = is;
  948. } else {
  949. stream_no_data = 0;
  950. }
  951. /* the following test is needed in case new streams appear
  952. dynamically in stream : we ignore them */
  953. if (pkt.stream_index >= file_table[file_index].nb_streams)
  954. goto discard_packet;
  955. ist_index = file_table[file_index].ist_index + pkt.stream_index;
  956. ist = ist_table[ist_index];
  957. if (ist->discard)
  958. goto discard_packet;
  959. if (pkt.flags & PKT_FLAG_DROPPED_FRAME)
  960. ist->frame_number++;
  961. if (do_hex_dump) {
  962. printf("stream #%d, size=%d:\n", pkt.stream_index, pkt.size);
  963. av_hex_dump(pkt.data, pkt.size);
  964. }
  965. // printf("read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
  966. len = pkt.size;
  967. ptr = pkt.data;
  968. while (len > 0) {
  969. /* decode the packet if needed */
  970. data_buf = NULL; /* fail safe */
  971. data_size = 0;
  972. if (ist->decoding_needed) {
  973. switch(ist->st->codec.codec_type) {
  974. case CODEC_TYPE_AUDIO:
  975. /* XXX: could avoid copy if PCM 16 bits with same
  976. endianness as CPU */
  977. ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
  978. ptr, len);
  979. if (ret < 0)
  980. goto fail_decode;
  981. /* Some bug in mpeg audio decoder gives */
  982. /* data_size < 0, it seems they are overflows */
  983. if (data_size <= 0) {
  984. /* no audio frame */
  985. ptr += ret;
  986. len -= ret;
  987. continue;
  988. }
  989. data_buf = (UINT8 *)samples;
  990. break;
  991. case CODEC_TYPE_VIDEO:
  992. if (ist->st->codec.codec_id == CODEC_ID_RAWVIDEO) {
  993. int size;
  994. size = (ist->st->codec.width * ist->st->codec.height);
  995. avpicture_fill(&picture, ptr,
  996. ist->st->codec.pix_fmt,
  997. ist->st->codec.width,
  998. ist->st->codec.height);
  999. ret = len;
  1000. } else {
  1001. data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
  1002. ret = avcodec_decode_video(&ist->st->codec,
  1003. &picture, &got_picture, ptr, len);
  1004. if (ret < 0) {
  1005. fail_decode:
  1006. fprintf(stderr, "Error while decoding stream #%d.%d\n",
  1007. ist->file_index, ist->index);
  1008. av_free_packet(&pkt);
  1009. goto redo;
  1010. }
  1011. if (!got_picture) {
  1012. /* no picture yet */
  1013. ptr += ret;
  1014. len -= ret;
  1015. continue;
  1016. }
  1017. }
  1018. break;
  1019. default:
  1020. goto fail_decode;
  1021. }
  1022. } else {
  1023. data_buf = ptr;
  1024. data_size = len;
  1025. ret = len;
  1026. }
  1027. /* init tickers */
  1028. if (!ist->ticker_inited) {
  1029. switch (ist->st->codec.codec_type) {
  1030. case CODEC_TYPE_AUDIO:
  1031. ticker_init(&ist->pts_ticker,
  1032. (INT64)ist->st->codec.sample_rate,
  1033. (INT64)(1000000));
  1034. ist->ticker_inited = 1;
  1035. break;
  1036. case CODEC_TYPE_VIDEO:
  1037. ticker_init(&ist->pts_ticker,
  1038. (INT64)ist->st->r_frame_rate,
  1039. ((INT64)1000000 * FRAME_RATE_BASE));
  1040. ist->ticker_inited = 1;
  1041. break;
  1042. default:
  1043. av_abort();
  1044. }
  1045. }
  1046. /* update pts */
  1047. switch(ist->st->codec.codec_type) {
  1048. case CODEC_TYPE_AUDIO:
  1049. //ist->pts = (INT64)1000000 * ist->sample_index / ist->st->codec.sample_rate;
  1050. ist->pts = ticker_abs(&ist->pts_ticker, ist->sample_index);
  1051. ist->sample_index += data_size / (2 * ist->st->codec.channels);
  1052. ist->pts_increment = (INT64) (data_size / (2 * ist->st->codec.channels)) * 1000000 / ist->st->codec.sample_rate;
  1053. break;
  1054. case CODEC_TYPE_VIDEO:
  1055. ist->frame_number++;
  1056. //ist->pts = ((INT64)ist->frame_number * 1000000 * FRAME_RATE_BASE) /
  1057. // ist->st->codec.frame_rate;
  1058. ist->pts = ticker_abs(&ist->pts_ticker, ist->frame_number);
  1059. ist->pts_increment = ((INT64) 1000000 * FRAME_RATE_BASE) /
  1060. ist->st->codec.frame_rate;
  1061. break;
  1062. default:
  1063. av_abort();
  1064. }
  1065. ptr += ret;
  1066. len -= ret;
  1067. /* transcode raw format, encode packets and output them */
  1068. for(i=0;i<nb_ostreams;i++) {
  1069. int frame_size;
  1070. ost = ost_table[i];
  1071. if (ost->source_index == ist_index) {
  1072. os = output_files[ost->file_index];
  1073. if (ost->encoding_needed) {
  1074. switch(ost->st->codec.codec_type) {
  1075. case CODEC_TYPE_AUDIO:
  1076. do_audio_out(os, ost, ist, data_buf, data_size);
  1077. break;
  1078. case CODEC_TYPE_VIDEO:
  1079. do_video_out(os, ost, ist, &picture, &frame_size);
  1080. if (do_vstats)
  1081. do_video_stats(ost, ist, frame_size);
  1082. break;
  1083. default:
  1084. av_abort();
  1085. }
  1086. } else {
  1087. /* no reencoding needed : output the packet directly */
  1088. /* force the input stream PTS */
  1089. os->oformat->write_packet(os, ost->index, data_buf, data_size, pkt.pts);
  1090. }
  1091. }
  1092. }
  1093. }
  1094. discard_packet:
  1095. av_free_packet(&pkt);
  1096. /* dump report by using the first video and audio streams */
  1097. {
  1098. char buf[1024];
  1099. AVFormatContext *oc;
  1100. INT64 total_size, ti;
  1101. AVCodecContext *enc;
  1102. int frame_number, vid;
  1103. double bitrate, ti1;
  1104. static INT64 last_time;
  1105. if ((min_pts - last_time) >= 500000) {
  1106. last_time = min_pts;
  1107. oc = output_files[0];
  1108. total_size = url_ftell(&oc->pb);
  1109. buf[0] = '\0';
  1110. ti = MAXINT64;
  1111. vid = 0;
  1112. for(i=0;i<nb_ostreams;i++) {
  1113. ost = ost_table[i];
  1114. enc = &ost->st->codec;
  1115. ist = ist_table[ost->source_index];
  1116. if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
  1117. frame_number = ist->frame_number;
  1118. sprintf(buf + strlen(buf), "frame=%5d q=%2d ",
  1119. frame_number, enc->quality);
  1120. if (do_psnr)
  1121. sprintf(buf + strlen(buf), "PSNR=%6.2f ", enc->psnr_y);
  1122. vid = 1;
  1123. }
  1124. /* compute min pts value */
  1125. if (!ist->discard && ist->pts < ti) {
  1126. ti = ist->pts;
  1127. }
  1128. }
  1129. ti1 = (double)ti / 1000000.0;
  1130. if (ti1 < 0.01)
  1131. ti1 = 0.01;
  1132. bitrate = (double)(total_size * 8) / ti1 / 1000.0;
  1133. sprintf(buf + strlen(buf),
  1134. "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
  1135. (double)total_size / 1024, ti1, bitrate);
  1136. fprintf(stderr, "%s \r", buf);
  1137. fflush(stderr);
  1138. }
  1139. }
  1140. }
  1141. term_exit();
  1142. /* dump report by using the first video and audio streams */
  1143. {
  1144. char buf[1024];
  1145. AVFormatContext *oc;
  1146. INT64 total_size, ti;
  1147. AVCodecContext *enc;
  1148. int frame_number, vid;
  1149. double bitrate, ti1;
  1150. oc = output_files[0];
  1151. total_size = url_ftell(&oc->pb);
  1152. buf[0] = '\0';
  1153. ti = MAXINT64;
  1154. vid = 0;
  1155. for(i=0;i<nb_ostreams;i++) {
  1156. ost = ost_table[i];
  1157. enc = &ost->st->codec;
  1158. ist = ist_table[ost->source_index];
  1159. if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
  1160. frame_number = ist->frame_number;
  1161. sprintf(buf + strlen(buf), "frame=%5d q=%2d ",
  1162. frame_number, enc->quality);
  1163. if (do_psnr)
  1164. sprintf(buf + strlen(buf), "PSNR=%6.2f ", enc->psnr_y);
  1165. vid = 1;
  1166. }
  1167. /* compute min pts value */
  1168. if (!ist->discard && ist->pts < ti) {
  1169. ti = ist->pts;
  1170. }
  1171. }
  1172. ti1 = ti / 1000000.0;
  1173. if (ti1 < 0.01)
  1174. ti1 = 0.01;
  1175. bitrate = (double)(total_size * 8) / ti1 / 1000.0;
  1176. sprintf(buf + strlen(buf),
  1177. "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
  1178. (double)total_size / 1024, ti1, bitrate);
  1179. fprintf(stderr, "%s \n", buf);
  1180. }
  1181. /* close each encoder */
  1182. for(i=0;i<nb_ostreams;i++) {
  1183. ost = ost_table[i];
  1184. if (ost->encoding_needed) {
  1185. av_freep(&ost->st->codec.stats_in);
  1186. avcodec_close(&ost->st->codec);
  1187. }
  1188. }
  1189. /* close each decoder */
  1190. for(i=0;i<nb_istreams;i++) {
  1191. ist = ist_table[i];
  1192. if (ist->decoding_needed) {
  1193. avcodec_close(&ist->st->codec);
  1194. }
  1195. }
  1196. /* write the trailer if needed and close file */
  1197. for(i=0;i<nb_output_files;i++) {
  1198. os = output_files[i];
  1199. av_write_trailer(os);
  1200. }
  1201. /* finished ! */
  1202. ret = 0;
  1203. fail1:
  1204. av_free(file_table);
  1205. if (ist_table) {
  1206. for(i=0;i<nb_istreams;i++) {
  1207. ist = ist_table[i];
  1208. av_free(ist);
  1209. }
  1210. av_free(ist_table);
  1211. }
  1212. if (ost_table) {
  1213. for(i=0;i<nb_ostreams;i++) {
  1214. ost = ost_table[i];
  1215. if (ost) {
  1216. if (ost->logfile) {
  1217. fclose(ost->logfile);
  1218. ost->logfile = NULL;
  1219. }
  1220. fifo_free(&ost->fifo); /* works even if fifo is not
  1221. initialized but set to zero */
  1222. av_free(ost->pict_tmp.data[0]);
  1223. if (ost->video_resample)
  1224. img_resample_close(ost->img_resample_ctx);
  1225. if (ost->audio_resample)
  1226. audio_resample_close(ost->resample);
  1227. av_free(ost);
  1228. }
  1229. }
  1230. av_free(ost_table);
  1231. }
  1232. return ret;
  1233. fail:
  1234. ret = -ENOMEM;
  1235. goto fail1;
  1236. }
  1237. #if 0
  1238. int file_read(const char *filename)
  1239. {
  1240. URLContext *h;
  1241. unsigned char buffer[1024];
  1242. int len, i;
  1243. if (url_open(&h, filename, O_RDONLY) < 0) {
  1244. printf("could not open '%s'\n", filename);
  1245. return -1;
  1246. }
  1247. for(;;) {
  1248. len = url_read(h, buffer, sizeof(buffer));
  1249. if (len <= 0)
  1250. break;
  1251. for(i=0;i<len;i++) putchar(buffer[i]);
  1252. }
  1253. url_close(h);
  1254. return 0;
  1255. }
  1256. #endif
  1257. void show_licence(void)
  1258. {
  1259. printf(
  1260. "ffmpeg version " FFMPEG_VERSION "\n"
  1261. "Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n"
  1262. "This library is free software; you can redistribute it and/or\n"
  1263. "modify it under the terms of the GNU Lesser General Public\n"
  1264. "License as published by the Free Software Foundation; either\n"
  1265. "version 2 of the License, or (at your option) any later version.\n"
  1266. "\n"
  1267. "This library is distributed in the hope that it will be useful,\n"
  1268. "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
  1269. "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
  1270. "Lesser General Public License for more details.\n"
  1271. "\n"
  1272. "You should have received a copy of the GNU Lesser General Public\n"
  1273. "License along with this library; if not, write to the Free Software\n"
  1274. "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n"
  1275. );
  1276. exit(1);
  1277. }
  1278. void opt_format(const char *arg)
  1279. {
  1280. file_iformat = av_find_input_format(arg);
  1281. file_oformat = guess_format(arg, NULL, NULL);
  1282. if (!file_iformat && !file_oformat) {
  1283. fprintf(stderr, "Unknown input or output format: %s\n", arg);
  1284. exit(1);
  1285. }
  1286. }
  1287. void opt_video_bitrate(const char *arg)
  1288. {
  1289. video_bit_rate = atoi(arg) * 1000;
  1290. }
  1291. void opt_video_bitrate_tolerance(const char *arg)
  1292. {
  1293. video_bit_rate_tolerance = atoi(arg) * 1000;
  1294. }
  1295. void opt_video_bitrate_max(const char *arg)
  1296. {
  1297. video_rc_max_rate = atoi(arg) * 1000;
  1298. }
  1299. void opt_video_bitrate_min(const char *arg)
  1300. {
  1301. video_rc_min_rate = atoi(arg) * 1000;
  1302. }
  1303. void opt_video_buffer_size(const char *arg)
  1304. {
  1305. video_rc_buffer_size = atoi(arg) * 1000;
  1306. }
  1307. void opt_video_rc_eq(char *arg)
  1308. {
  1309. video_rc_eq = arg;
  1310. }
  1311. void opt_workaround_bugs(const char *arg)
  1312. {
  1313. workaround_bugs = atoi(arg);
  1314. }
  1315. void opt_dct_algo(const char *arg)
  1316. {
  1317. dct_algo = atoi(arg);
  1318. }
  1319. void opt_idct_algo(const char *arg)
  1320. {
  1321. idct_algo = atoi(arg);
  1322. }
  1323. void opt_error_resilience(const char *arg)
  1324. {
  1325. error_resilience = atoi(arg);
  1326. }
  1327. void opt_error_concealment(const char *arg)
  1328. {
  1329. error_concealment = atoi(arg);
  1330. }
  1331. void opt_frame_rate(const char *arg)
  1332. {
  1333. frame_rate = (int)(strtod(arg, 0) * FRAME_RATE_BASE);
  1334. }
  1335. void opt_frame_crop_top(const char *arg)
  1336. {
  1337. frame_topBand = atoi(arg);
  1338. if (frame_topBand < 0) {
  1339. fprintf(stderr, "Incorrect top crop size\n");
  1340. exit(1);
  1341. }
  1342. if ((frame_topBand % 2) != 0) {
  1343. fprintf(stderr, "Top crop size must be a multiple of 2\n");
  1344. exit(1);
  1345. }
  1346. if ((frame_topBand) >= frame_height){
  1347. fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
  1348. exit(1);
  1349. }
  1350. frame_height -= frame_topBand;
  1351. }
  1352. void opt_frame_crop_bottom(const char *arg)
  1353. {
  1354. frame_bottomBand = atoi(arg);
  1355. if (frame_bottomBand < 0) {
  1356. fprintf(stderr, "Incorrect bottom crop size\n");
  1357. exit(1);
  1358. }
  1359. if ((frame_bottomBand % 2) != 0) {
  1360. fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
  1361. exit(1);
  1362. }
  1363. if ((frame_bottomBand) >= frame_height){
  1364. fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
  1365. exit(1);
  1366. }
  1367. frame_height -= frame_bottomBand;
  1368. }
  1369. void opt_frame_crop_left(const char *arg)
  1370. {
  1371. frame_leftBand = atoi(arg);
  1372. if (frame_leftBand < 0) {
  1373. fprintf(stderr, "Incorrect left crop size\n");
  1374. exit(1);
  1375. }
  1376. if ((frame_leftBand % 2) != 0) {
  1377. fprintf(stderr, "Left crop size must be a multiple of 2\n");
  1378. exit(1);
  1379. }
  1380. if ((frame_leftBand) >= frame_width){
  1381. fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
  1382. exit(1);
  1383. }
  1384. frame_width -= frame_leftBand;
  1385. }
  1386. void opt_frame_crop_right(const char *arg)
  1387. {
  1388. frame_rightBand = atoi(arg);
  1389. if (frame_rightBand < 0) {
  1390. fprintf(stderr, "Incorrect right crop size\n");
  1391. exit(1);
  1392. }
  1393. if ((frame_rightBand % 2) != 0) {
  1394. fprintf(stderr, "Right crop size must be a multiple of 2\n");
  1395. exit(1);
  1396. }
  1397. if ((frame_rightBand) >= frame_width){
  1398. fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
  1399. exit(1);
  1400. }
  1401. frame_width -= frame_rightBand;
  1402. }
  1403. void opt_frame_size(const char *arg)
  1404. {
  1405. parse_image_size(&frame_width, &frame_height, arg);
  1406. if (frame_width <= 0 || frame_height <= 0) {
  1407. fprintf(stderr, "Incorrect frame size\n");
  1408. exit(1);
  1409. }
  1410. if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
  1411. fprintf(stderr, "Frame size must be a multiple of 2\n");
  1412. exit(1);
  1413. }
  1414. }
  1415. void opt_gop_size(const char *arg)
  1416. {
  1417. gop_size = atoi(arg);
  1418. }
  1419. void opt_b_frames(const char *arg)
  1420. {
  1421. b_frames = atoi(arg);
  1422. if (b_frames > FF_MAX_B_FRAMES) {
  1423. fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
  1424. exit(1);
  1425. } else if (b_frames < 1) {
  1426. fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
  1427. exit(1);
  1428. }
  1429. }
  1430. void opt_qscale(const char *arg)
  1431. {
  1432. video_qscale = atoi(arg);
  1433. if (video_qscale < 0 ||
  1434. video_qscale > 31) {
  1435. fprintf(stderr, "qscale must be >= 1 and <= 31\n");
  1436. exit(1);
  1437. }
  1438. }
  1439. void opt_qmin(const char *arg)
  1440. {
  1441. video_qmin = atoi(arg);
  1442. if (video_qmin < 0 ||
  1443. video_qmin > 31) {
  1444. fprintf(stderr, "qmin must be >= 1 and <= 31\n");
  1445. exit(1);
  1446. }
  1447. }
  1448. void opt_qmax(const char *arg)
  1449. {
  1450. video_qmax = atoi(arg);
  1451. if (video_qmax < 0 ||
  1452. video_qmax > 31) {
  1453. fprintf(stderr, "qmax must be >= 1 and <= 31\n");
  1454. exit(1);
  1455. }
  1456. }
  1457. void opt_qdiff(const char *arg)
  1458. {
  1459. video_qdiff = atoi(arg);
  1460. if (video_qdiff < 0 ||
  1461. video_qdiff > 31) {
  1462. fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
  1463. exit(1);
  1464. }
  1465. }
  1466. void opt_qblur(const char *arg)
  1467. {
  1468. video_qblur = atof(arg);
  1469. }
  1470. void opt_qcomp(const char *arg)
  1471. {
  1472. video_qcomp = atof(arg);
  1473. }
  1474. void opt_b_qfactor(const char *arg)
  1475. {
  1476. video_b_qfactor = atof(arg);
  1477. }
  1478. void opt_i_qfactor(const char *arg)
  1479. {
  1480. video_i_qfactor = atof(arg);
  1481. }
  1482. void opt_b_qoffset(const char *arg)
  1483. {
  1484. video_b_qoffset = atof(arg);
  1485. }
  1486. void opt_i_qoffset(const char *arg)
  1487. {
  1488. video_i_qoffset = atof(arg);
  1489. }
  1490. void opt_packet_size(const char *arg)
  1491. {
  1492. packet_size= atoi(arg);
  1493. }
  1494. void opt_audio_bitrate(const char *arg)
  1495. {
  1496. audio_bit_rate = atoi(arg) * 1000;
  1497. }
  1498. void opt_audio_rate(const char *arg)
  1499. {
  1500. audio_sample_rate = atoi(arg);
  1501. }
  1502. void opt_audio_channels(const char *arg)
  1503. {
  1504. audio_channels = atoi(arg);
  1505. }
  1506. void opt_video_device(const char *arg)
  1507. {
  1508. v4l_device = strdup(arg);
  1509. }
  1510. void opt_audio_device(const char *arg)
  1511. {
  1512. audio_device = strdup(arg);
  1513. }
  1514. void opt_audio_codec(const char *arg)
  1515. {
  1516. AVCodec *p;
  1517. if (!strcmp(arg, "copy")) {
  1518. audio_stream_copy = 1;
  1519. } else {
  1520. p = first_avcodec;
  1521. while (p) {
  1522. if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
  1523. break;
  1524. p = p->next;
  1525. }
  1526. if (p == NULL) {
  1527. fprintf(stderr, "Unknown audio codec '%s'\n", arg);
  1528. exit(1);
  1529. } else {
  1530. audio_codec_id = p->id;
  1531. }
  1532. }
  1533. }
  1534. const char *motion_str[] = {
  1535. "zero",
  1536. "full",
  1537. "log",
  1538. "phods",
  1539. "epzs",
  1540. "x1",
  1541. NULL,
  1542. };
  1543. void opt_motion_estimation(const char *arg)
  1544. {
  1545. const char **p;
  1546. p = motion_str;
  1547. for(;;) {
  1548. if (!*p) {
  1549. fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
  1550. exit(1);
  1551. }
  1552. if (!strcmp(*p, arg))
  1553. break;
  1554. p++;
  1555. }
  1556. me_method = (p - motion_str) + 1;
  1557. }
  1558. void opt_video_codec(const char *arg)
  1559. {
  1560. AVCodec *p;
  1561. if (!strcmp(arg, "copy")) {
  1562. video_stream_copy = 1;
  1563. } else {
  1564. p = first_avcodec;
  1565. while (p) {
  1566. if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
  1567. break;
  1568. p = p->next;
  1569. }
  1570. if (p == NULL) {
  1571. fprintf(stderr, "Unknown video codec '%s'\n", arg);
  1572. exit(1);
  1573. } else {
  1574. video_codec_id = p->id;
  1575. }
  1576. }
  1577. }
  1578. void opt_map(const char *arg)
  1579. {
  1580. AVStreamMap *m;
  1581. const char *p;
  1582. p = arg;
  1583. m = &stream_maps[nb_stream_maps++];
  1584. m->file_index = strtol(arg, (char **)&p, 0);
  1585. if (*p)
  1586. p++;
  1587. m->stream_index = strtol(p, (char **)&p, 0);
  1588. }
  1589. void opt_recording_time(const char *arg)
  1590. {
  1591. recording_time = parse_date(arg, 1);
  1592. }
  1593. void print_error(const char *filename, int err)
  1594. {
  1595. switch(err) {
  1596. case AVERROR_NUMEXPECTED:
  1597. fprintf(stderr, "%s: Incorrect image filename syntax.\n"
  1598. "Use '%%d' to specify the image number:\n"
  1599. " for img1.jpg, img2.jpg, ..., use 'img%%d.jpg';\n"
  1600. " for img001.jpg, img002.jpg, ..., use 'img%%03d.jpg'.\n",
  1601. filename);
  1602. break;
  1603. case AVERROR_INVALIDDATA:
  1604. fprintf(stderr, "%s: Error while parsing header\n", filename);
  1605. break;
  1606. case AVERROR_NOFMT:
  1607. fprintf(stderr, "%s: Unknown format\n", filename);
  1608. break;
  1609. default:
  1610. fprintf(stderr, "%s: Error while opening file\n", filename);
  1611. break;
  1612. }
  1613. }
  1614. void opt_input_file(const char *filename)
  1615. {
  1616. AVFormatContext *ic;
  1617. AVFormatParameters params, *ap = &params;
  1618. int err, i, ret, rfps;
  1619. /* get default parameters from command line */
  1620. memset(ap, 0, sizeof(*ap));
  1621. ap->sample_rate = audio_sample_rate;
  1622. ap->channels = audio_channels;
  1623. ap->frame_rate = frame_rate;
  1624. ap->width = frame_width;
  1625. ap->height = frame_height;
  1626. /* open the input file with generic libav function */
  1627. err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
  1628. if (err < 0) {
  1629. print_error(filename, err);
  1630. exit(1);
  1631. }
  1632. /* If not enough info to get the stream parameters, we decode the
  1633. first frames to get it. (used in mpeg case for example) */
  1634. ret = av_find_stream_info(ic);
  1635. if (ret < 0) {
  1636. fprintf(stderr, "%s: could not find codec parameters\n", filename);
  1637. exit(1);
  1638. }
  1639. /* update the current parameters so that they match the one of the input stream */
  1640. for(i=0;i<ic->nb_streams;i++) {
  1641. AVCodecContext *enc = &ic->streams[i]->codec;
  1642. switch(enc->codec_type) {
  1643. case CODEC_TYPE_AUDIO:
  1644. //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
  1645. audio_channels = enc->channels;
  1646. audio_sample_rate = enc->sample_rate;
  1647. break;
  1648. case CODEC_TYPE_VIDEO:
  1649. frame_height = enc->height;
  1650. frame_width = enc->width;
  1651. rfps = ic->streams[i]->r_frame_rate;
  1652. enc->workaround_bugs = workaround_bugs;
  1653. enc->error_resilience = error_resilience;
  1654. enc->error_concealment = error_concealment;
  1655. enc->idct_algo= idct_algo;
  1656. if (enc->frame_rate != rfps) {
  1657. fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",
  1658. i, (float)enc->frame_rate / FRAME_RATE_BASE,
  1659. (float)rfps / FRAME_RATE_BASE);
  1660. }
  1661. /* update the current frame rate to match the stream frame rate */
  1662. frame_rate = rfps;
  1663. break;
  1664. default:
  1665. av_abort();
  1666. }
  1667. }
  1668. input_files[nb_input_files] = ic;
  1669. /* dump the file content */
  1670. dump_format(ic, nb_input_files, filename, 0);
  1671. nb_input_files++;
  1672. file_iformat = NULL;
  1673. file_oformat = NULL;
  1674. }
  1675. void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
  1676. {
  1677. int has_video, has_audio, i, j;
  1678. AVFormatContext *ic;
  1679. has_video = 0;
  1680. has_audio = 0;
  1681. for(j=0;j<nb_input_files;j++) {
  1682. ic = input_files[j];
  1683. for(i=0;i<ic->nb_streams;i++) {
  1684. AVCodecContext *enc = &ic->streams[i]->codec;
  1685. switch(enc->codec_type) {
  1686. case CODEC_TYPE_AUDIO:
  1687. has_audio = 1;
  1688. break;
  1689. case CODEC_TYPE_VIDEO:
  1690. has_video = 1;
  1691. break;
  1692. default:
  1693. av_abort();
  1694. }
  1695. }
  1696. }
  1697. *has_video_ptr = has_video;
  1698. *has_audio_ptr = has_audio;
  1699. }
  1700. void opt_output_file(const char *filename)
  1701. {
  1702. AVStream *st;
  1703. AVFormatContext *oc;
  1704. int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
  1705. int codec_id;
  1706. if (!strcmp(filename, "-"))
  1707. filename = "pipe:";
  1708. oc = av_mallocz(sizeof(AVFormatContext));
  1709. if (!file_oformat) {
  1710. file_oformat = guess_format(NULL, filename, NULL);
  1711. if (!file_oformat) {
  1712. fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
  1713. filename);
  1714. exit(1);
  1715. }
  1716. }
  1717. oc->oformat = file_oformat;
  1718. if (!strcmp(file_oformat->name, "ffm") &&
  1719. strstart(filename, "http:", NULL)) {
  1720. /* special case for files sent to ffserver: we get the stream
  1721. parameters from ffserver */
  1722. if (read_ffserver_streams(oc, filename) < 0) {
  1723. fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
  1724. exit(1);
  1725. }
  1726. } else {
  1727. use_video = file_oformat->video_codec != CODEC_ID_NONE;
  1728. use_audio = file_oformat->audio_codec != CODEC_ID_NONE;
  1729. /* disable if no corresponding type found and at least one
  1730. input file */
  1731. if (nb_input_files > 0) {
  1732. check_audio_video_inputs(&input_has_video, &input_has_audio);
  1733. if (!input_has_video)
  1734. use_video = 0;
  1735. if (!input_has_audio)
  1736. use_audio = 0;
  1737. }
  1738. /* manual disable */
  1739. if (audio_disable) {
  1740. use_audio = 0;
  1741. }
  1742. if (video_disable) {
  1743. use_video = 0;
  1744. }
  1745. nb_streams = 0;
  1746. if (use_video) {
  1747. AVCodecContext *video_enc;
  1748. st = av_mallocz(sizeof(AVStream));
  1749. if (!st) {
  1750. fprintf(stderr, "Could not alloc stream\n");
  1751. exit(1);
  1752. }
  1753. video_enc = &st->codec;
  1754. if (video_stream_copy) {
  1755. st->stream_copy = 1;
  1756. video_enc->codec_type = CODEC_TYPE_VIDEO;
  1757. } else {
  1758. codec_id = file_oformat->video_codec;
  1759. if (video_codec_id != CODEC_ID_NONE)
  1760. codec_id = video_codec_id;
  1761. video_enc->codec_id = codec_id;
  1762. video_enc->bit_rate = video_bit_rate;
  1763. video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
  1764. video_enc->frame_rate = frame_rate;
  1765. video_enc->width = frame_width;
  1766. video_enc->height = frame_height;
  1767. if (!intra_only)
  1768. video_enc->gop_size = gop_size;
  1769. else
  1770. video_enc->gop_size = 0;
  1771. if (video_qscale || same_quality) {
  1772. video_enc->flags |= CODEC_FLAG_QSCALE;
  1773. video_enc->quality = video_qscale;
  1774. }
  1775. if (use_hq) {
  1776. video_enc->flags |= CODEC_FLAG_HQ;
  1777. }
  1778. if (use_4mv) {
  1779. video_enc->flags |= CODEC_FLAG_HQ;
  1780. video_enc->flags |= CODEC_FLAG_4MV;
  1781. }
  1782. if(use_part)
  1783. video_enc->flags |= CODEC_FLAG_PART;
  1784. if (b_frames) {
  1785. if (codec_id != CODEC_ID_MPEG4) {
  1786. fprintf(stderr, "\nB frames encoding only supported by MPEG-4.\n");
  1787. exit(1);
  1788. }
  1789. video_enc->max_b_frames = b_frames;
  1790. video_enc->b_frame_strategy = 0;
  1791. video_enc->b_quant_factor = 2.0;
  1792. }
  1793. video_enc->qmin = video_qmin;
  1794. video_enc->qmax = video_qmax;
  1795. video_enc->max_qdiff = video_qdiff;
  1796. video_enc->qblur = video_qblur;
  1797. video_enc->qcompress = video_qcomp;
  1798. video_enc->rc_eq = video_rc_eq;
  1799. video_enc->rc_max_rate = video_rc_max_rate;
  1800. video_enc->rc_min_rate = video_rc_min_rate;
  1801. video_enc->rc_buffer_size = video_rc_buffer_size;
  1802. video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
  1803. video_enc->i_quant_factor = video_i_qfactor;
  1804. video_enc->b_quant_factor = video_b_qfactor;
  1805. video_enc->i_quant_offset = video_i_qoffset;
  1806. video_enc->b_quant_offset = video_b_qoffset;
  1807. video_enc->dct_algo = dct_algo;
  1808. video_enc->idct_algo = idct_algo;
  1809. if(packet_size){
  1810. video_enc->rtp_mode= 1;
  1811. video_enc->rtp_payload_size= packet_size;
  1812. }
  1813. if (do_psnr)
  1814. video_enc->get_psnr = 1;
  1815. else
  1816. video_enc->get_psnr = 0;
  1817. video_enc->me_method = me_method;
  1818. /* two pass mode */
  1819. if (do_pass) {
  1820. if (do_pass == 1) {
  1821. video_enc->flags |= CODEC_FLAG_PASS1;
  1822. } else {
  1823. video_enc->flags |= CODEC_FLAG_PASS2;
  1824. }
  1825. }
  1826. /* XXX: need to find a way to set codec parameters */
  1827. if (oc->oformat->flags & AVFMT_RGB24) {
  1828. video_enc->pix_fmt = PIX_FMT_RGB24;
  1829. }
  1830. }
  1831. oc->streams[nb_streams] = st;
  1832. nb_streams++;
  1833. }
  1834. if (use_audio) {
  1835. AVCodecContext *audio_enc;
  1836. st = av_mallocz(sizeof(AVStream));
  1837. if (!st) {
  1838. fprintf(stderr, "Could not alloc stream\n");
  1839. exit(1);
  1840. }
  1841. audio_enc = &st->codec;
  1842. audio_enc->codec_type = CODEC_TYPE_AUDIO;
  1843. if (audio_stream_copy) {
  1844. st->stream_copy = 1;
  1845. } else {
  1846. codec_id = file_oformat->audio_codec;
  1847. if (audio_codec_id != CODEC_ID_NONE)
  1848. codec_id = audio_codec_id;
  1849. audio_enc->codec_id = codec_id;
  1850. audio_enc->bit_rate = audio_bit_rate;
  1851. audio_enc->sample_rate = audio_sample_rate;
  1852. /* For audio codecs other than AC3 we limit */
  1853. /* the number of coded channels to stereo */
  1854. if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
  1855. audio_enc->channels = 2;
  1856. } else
  1857. audio_enc->channels = audio_channels;
  1858. }
  1859. oc->streams[nb_streams] = st;
  1860. nb_streams++;
  1861. }
  1862. oc->nb_streams = nb_streams;
  1863. if (!nb_streams) {
  1864. fprintf(stderr, "No audio or video streams available\n");
  1865. exit(1);
  1866. }
  1867. if (str_title)
  1868. pstrcpy(oc->title, sizeof(oc->title), str_title);
  1869. if (str_author)
  1870. pstrcpy(oc->author, sizeof(oc->author), str_author);
  1871. if (str_copyright)
  1872. pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
  1873. if (str_comment)
  1874. pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
  1875. }
  1876. output_files[nb_output_files++] = oc;
  1877. strcpy(oc->filename, filename);
  1878. /* check filename in case of an image number is expected */
  1879. if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
  1880. if (filename_number_test(oc->filename) < 0) {
  1881. print_error(oc->filename, AVERROR_NUMEXPECTED);
  1882. exit(1);
  1883. }
  1884. }
  1885. if (!(oc->oformat->flags & AVFMT_NOFILE)) {
  1886. /* test if it already exists to avoid loosing precious files */
  1887. if (!file_overwrite &&
  1888. (strchr(filename, ':') == NULL ||
  1889. strstart(filename, "file:", NULL))) {
  1890. if (url_exist(filename)) {
  1891. int c;
  1892. printf("File '%s' already exists. Overwrite ? [y/N] ", filename);
  1893. fflush(stdout);
  1894. c = getchar();
  1895. if (toupper(c) != 'Y') {
  1896. fprintf(stderr, "Not overwriting - exiting\n");
  1897. exit(1);
  1898. }
  1899. }
  1900. }
  1901. /* open the file */
  1902. if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
  1903. fprintf(stderr, "Could not open '%s'\n", filename);
  1904. exit(1);
  1905. }
  1906. }
  1907. /* reset some options */
  1908. file_oformat = NULL;
  1909. file_iformat = NULL;
  1910. audio_disable = 0;
  1911. video_disable = 0;
  1912. audio_codec_id = CODEC_ID_NONE;
  1913. video_codec_id = CODEC_ID_NONE;
  1914. audio_stream_copy = 0;
  1915. video_stream_copy = 0;
  1916. }
  1917. /* prepare dummy protocols for grab */
  1918. void prepare_grab(void)
  1919. {
  1920. int has_video, has_audio, i, j;
  1921. AVFormatContext *oc;
  1922. AVFormatContext *ic;
  1923. AVFormatParameters ap1, *ap = &ap1;
  1924. /* see if audio/video inputs are needed */
  1925. has_video = 0;
  1926. has_audio = 0;
  1927. memset(ap, 0, sizeof(*ap));
  1928. for(j=0;j<nb_output_files;j++) {
  1929. oc = output_files[j];
  1930. for(i=0;i<oc->nb_streams;i++) {
  1931. AVCodecContext *enc = &oc->streams[i]->codec;
  1932. switch(enc->codec_type) {
  1933. case CODEC_TYPE_AUDIO:
  1934. if (enc->sample_rate > ap->sample_rate)
  1935. ap->sample_rate = enc->sample_rate;
  1936. if (enc->channels > ap->channels)
  1937. ap->channels = enc->channels;
  1938. has_audio = 1;
  1939. break;
  1940. case CODEC_TYPE_VIDEO:
  1941. if (enc->width > ap->width)
  1942. ap->width = enc->width;
  1943. if (enc->height > ap->height)
  1944. ap->height = enc->height;
  1945. if (enc->frame_rate > ap->frame_rate)
  1946. ap->frame_rate = enc->frame_rate;
  1947. has_video = 1;
  1948. break;
  1949. default:
  1950. av_abort();
  1951. }
  1952. }
  1953. }
  1954. if (has_video == 0 && has_audio == 0) {
  1955. fprintf(stderr, "Output file must have at least one audio or video stream\n");
  1956. exit(1);
  1957. }
  1958. if (has_video) {
  1959. AVInputFormat *fmt1;
  1960. fmt1 = av_find_input_format("video_grab_device");
  1961. if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
  1962. fprintf(stderr, "Could not find video grab device\n");
  1963. exit(1);
  1964. }
  1965. /* by now video grab has one stream */
  1966. ic->streams[0]->r_frame_rate = ap->frame_rate;
  1967. input_files[nb_input_files] = ic;
  1968. dump_format(ic, nb_input_files, v4l_device, 0);
  1969. nb_input_files++;
  1970. }
  1971. if (has_audio) {
  1972. AVInputFormat *fmt1;
  1973. fmt1 = av_find_input_format("audio_device");
  1974. if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
  1975. fprintf(stderr, "Could not find audio grab device\n");
  1976. exit(1);
  1977. }
  1978. input_files[nb_input_files] = ic;
  1979. dump_format(ic, nb_input_files, audio_device, 0);
  1980. nb_input_files++;
  1981. }
  1982. }
  1983. /* open the necessary output devices for playing */
  1984. void prepare_play(void)
  1985. {
  1986. file_iformat = NULL;
  1987. file_oformat = guess_format("audio_device", NULL, NULL);
  1988. if (!file_oformat) {
  1989. fprintf(stderr, "Could not find audio device\n");
  1990. exit(1);
  1991. }
  1992. opt_output_file(audio_device);
  1993. }
  1994. /* same option as mencoder */
  1995. void opt_pass(const char *pass_str)
  1996. {
  1997. int pass;
  1998. pass = atoi(pass_str);
  1999. if (pass != 1 && pass != 2) {
  2000. fprintf(stderr, "pass number can be only 1 or 2\n");
  2001. exit(1);
  2002. }
  2003. do_pass = pass;
  2004. }
  2005. #ifndef CONFIG_WIN32
  2006. INT64 getutime(void)
  2007. {
  2008. struct rusage rusage;
  2009. getrusage(RUSAGE_SELF, &rusage);
  2010. return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
  2011. }
  2012. #else
  2013. INT64 getutime(void)
  2014. {
  2015. return av_gettime();
  2016. }
  2017. #endif
  2018. extern int ffm_nopts;
  2019. void opt_bitexact(void)
  2020. {
  2021. avcodec_set_bit_exact();
  2022. /* disable generate of real time pts in ffm (need to be supressed anyway) */
  2023. ffm_nopts = 1;
  2024. }
  2025. void show_formats(void)
  2026. {
  2027. AVInputFormat *ifmt;
  2028. AVOutputFormat *ofmt;
  2029. URLProtocol *up;
  2030. AVCodec *p;
  2031. const char **pp;
  2032. printf("File formats:\n");
  2033. printf(" Encoding:");
  2034. for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
  2035. printf(" %s", ofmt->name);
  2036. }
  2037. printf("\n");
  2038. printf(" Decoding:");
  2039. for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
  2040. printf(" %s", ifmt->name);
  2041. }
  2042. printf("\n");
  2043. printf("Codecs:\n");
  2044. printf(" Encoders:");
  2045. for(p = first_avcodec; p != NULL; p = p->next) {
  2046. if (p->encode)
  2047. printf(" %s", p->name);
  2048. }
  2049. printf("\n");
  2050. printf(" Decoders:");
  2051. for(p = first_avcodec; p != NULL; p = p->next) {
  2052. if (p->decode)
  2053. printf(" %s", p->name);
  2054. }
  2055. printf("\n");
  2056. printf("Supported file protocols:");
  2057. for(up = first_protocol; up != NULL; up = up->next)
  2058. printf(" %s:", up->name);
  2059. printf("\n");
  2060. printf("Frame size abbreviations: sqcif qcif cif 4cif\n");
  2061. printf("Motion estimation methods:");
  2062. pp = motion_str;
  2063. while (*pp) {
  2064. printf(" %s", *pp);
  2065. if ((pp - motion_str + 1) == ME_ZERO)
  2066. printf("(fastest)");
  2067. else if ((pp - motion_str + 1) == ME_FULL)
  2068. printf("(slowest)");
  2069. else if ((pp - motion_str + 1) == ME_EPZS)
  2070. printf("(default)");
  2071. pp++;
  2072. }
  2073. printf("\n");
  2074. exit(1);
  2075. }
  2076. void show_help(void)
  2077. {
  2078. const char *prog;
  2079. const OptionDef *po;
  2080. int i, expert;
  2081. prog = do_play ? "ffplay" : "ffmpeg";
  2082. printf("%s version " FFMPEG_VERSION ", Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n",
  2083. prog);
  2084. if (!do_play) {
  2085. printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
  2086. "Hyper fast MPEG1/MPEG4/H263/RV and AC3/MPEG audio encoder\n");
  2087. } else {
  2088. printf("usage: ffplay [options] input_file...\n"
  2089. "Simple audio player\n");
  2090. }
  2091. printf("\n"
  2092. "Main options are:\n");
  2093. for(i=0;i<2;i++) {
  2094. if (i == 1)
  2095. printf("\nAdvanced options are:\n");
  2096. for(po = options; po->name != NULL; po++) {
  2097. char buf[64];
  2098. expert = (po->flags & OPT_EXPERT) != 0;
  2099. if (expert == i) {
  2100. strcpy(buf, po->name);
  2101. if (po->flags & HAS_ARG) {
  2102. strcat(buf, " ");
  2103. strcat(buf, po->argname);
  2104. }
  2105. printf("-%-17s %s\n", buf, po->help);
  2106. }
  2107. }
  2108. }
  2109. exit(1);
  2110. }
  2111. const OptionDef options[] = {
  2112. { "L", 0, {(void*)show_licence}, "show license" },
  2113. { "h", 0, {(void*)show_help}, "show help" },
  2114. { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
  2115. { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
  2116. { "vcd", OPT_BOOL, {(void*)&mpeg_vcd}, "output Video CD MPEG-PS compliant file" },
  2117. { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
  2118. { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
  2119. { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
  2120. { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
  2121. { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
  2122. { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
  2123. { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
  2124. { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
  2125. { "pass", HAS_ARG, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
  2126. { "passlogfile", HAS_ARG | OPT_STRING, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
  2127. /* video options */
  2128. { "b", HAS_ARG, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
  2129. { "r", HAS_ARG, {(void*)opt_frame_rate}, "set frame rate (in Hz)", "rate" },
  2130. { "s", HAS_ARG, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
  2131. { "croptop", HAS_ARG, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
  2132. { "cropbottom", HAS_ARG, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
  2133. { "cropleft", HAS_ARG, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
  2134. { "cropright", HAS_ARG, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
  2135. { "g", HAS_ARG | OPT_EXPERT, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
  2136. { "intra", OPT_BOOL | OPT_EXPERT, {(void*)&intra_only}, "use only intra frames"},
  2137. { "vn", OPT_BOOL, {(void*)&video_disable}, "disable video" },
  2138. { "qscale", HAS_ARG | OPT_EXPERT, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
  2139. { "qmin", HAS_ARG | OPT_EXPERT, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
  2140. { "qmax", HAS_ARG | OPT_EXPERT, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
  2141. { "qdiff", HAS_ARG | OPT_EXPERT, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
  2142. { "qblur", HAS_ARG | OPT_EXPERT, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
  2143. { "qcomp", HAS_ARG | OPT_EXPERT, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
  2144. { "b_qfactor", HAS_ARG | OPT_EXPERT, {(void*)opt_b_qfactor}, "qp factor between p and b frames", "factor" },
  2145. { "i_qfactor", HAS_ARG | OPT_EXPERT, {(void*)opt_i_qfactor}, "qp factor between p and i frames", "factor" },
  2146. { "b_qoffset", HAS_ARG | OPT_EXPERT, {(void*)opt_b_qoffset}, "qp offset between p and b frames", "offset" },
  2147. { "i_qoffset", HAS_ARG | OPT_EXPERT, {(void*)opt_i_qoffset}, "qp offset between p and i frames", "offset" },
  2148. { "rc_eq", HAS_ARG | OPT_EXPERT, {(void*)opt_video_rc_eq}, "", "equation" },
  2149. { "bt", HAS_ARG, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
  2150. { "maxrate", HAS_ARG, {(void*)opt_video_bitrate_max}, "set max video bitrate tolerance (in kbit/s)", "bitrate" },
  2151. { "minrate", HAS_ARG, {(void*)opt_video_bitrate_min}, "set min video bitrate tolerance (in kbit/s)", "bitrate" },
  2152. { "bufsize", HAS_ARG, {(void*)opt_video_buffer_size}, "set ratecontrol buffere size (in kbit)", "size" },
  2153. { "vd", HAS_ARG | OPT_EXPERT, {(void*)opt_video_device}, "set video grab device", "device" },
  2154. { "vcodec", HAS_ARG | OPT_EXPERT, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
  2155. { "me", HAS_ARG | OPT_EXPERT, {(void*)opt_motion_estimation}, "set motion estimation method",
  2156. "method" },
  2157. { "dct_algo", HAS_ARG | OPT_EXPERT, {(void*)opt_dct_algo}, "set dct algo", "algo" },
  2158. { "idct_algo", HAS_ARG | OPT_EXPERT, {(void*)opt_idct_algo}, "set idct algo", "algo" },
  2159. { "er", HAS_ARG | OPT_EXPERT, {(void*)opt_error_resilience}, "set error resilience", "" },
  2160. { "ec", HAS_ARG | OPT_EXPERT, {(void*)opt_error_resilience}, "set error concealment", "" },
  2161. { "bf", HAS_ARG | OPT_EXPERT, {(void*)opt_b_frames}, "use 'frames' B frames (only MPEG-4)", "frames" },
  2162. { "hq", OPT_BOOL | OPT_EXPERT, {(void*)&use_hq}, "activate high quality settings" },
  2163. { "4mv", OPT_BOOL | OPT_EXPERT, {(void*)&use_4mv}, "use four motion vector by macroblock (only MPEG-4)" },
  2164. { "part", OPT_BOOL | OPT_EXPERT, {(void*)&use_part}, "use data partitioning (only MPEG-4)" },
  2165. { "bug", HAS_ARG | OPT_EXPERT, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
  2166. { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "packet size", "size in bits" },
  2167. { "sameq", OPT_BOOL, {(void*)&same_quality},
  2168. "use same video quality as source (implies VBR)" },
  2169. /* audio options */
  2170. { "ab", HAS_ARG, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
  2171. { "ar", HAS_ARG, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
  2172. { "ac", HAS_ARG, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
  2173. { "an", OPT_BOOL, {(void*)&audio_disable}, "disable audio" },
  2174. { "ad", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_device}, "set audio device", "device" },
  2175. { "acodec", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
  2176. { "deinterlace", OPT_BOOL | OPT_EXPERT, {(void*)&do_deinterlace},
  2177. "deinterlace pictures" },
  2178. { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
  2179. "add timings for benchmarking" },
  2180. { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
  2181. "dump each input packet" },
  2182. { "psnr", OPT_BOOL | OPT_EXPERT, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
  2183. { "vstats", OPT_BOOL | OPT_EXPERT, {(void*)&do_vstats}, "dump video coding statistics to file" },
  2184. { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" },
  2185. { NULL, },
  2186. };
  2187. int main(int argc, char **argv)
  2188. {
  2189. int optindex, i;
  2190. const char *opt, *arg;
  2191. const OptionDef *po;
  2192. INT64 ti;
  2193. av_register_all();
  2194. /* detect if invoked as player */
  2195. i = strlen(argv[0]);
  2196. if (i >= 6 && !strcmp(argv[0] + i - 6, "ffplay"))
  2197. do_play = 1;
  2198. if (argc <= 1)
  2199. show_help();
  2200. /* parse options */
  2201. optindex = 1;
  2202. while (optindex < argc) {
  2203. opt = argv[optindex++];
  2204. if (opt[0] == '-' && opt[1] != '\0') {
  2205. po = options;
  2206. while (po->name != NULL) {
  2207. if (!strcmp(opt + 1, po->name))
  2208. break;
  2209. po++;
  2210. }
  2211. if (!po->name) {
  2212. fprintf(stderr, "%s: unrecognized option '%s'\n", argv[0], opt);
  2213. exit(1);
  2214. }
  2215. arg = NULL;
  2216. if (po->flags & HAS_ARG)
  2217. arg = argv[optindex++];
  2218. if (po->flags & OPT_STRING) {
  2219. char *str;
  2220. str = strdup(arg);
  2221. *po->u.str_arg = str;
  2222. } else if (po->flags & OPT_BOOL) {
  2223. *po->u.int_arg = 1;
  2224. } else {
  2225. po->u.func_arg(arg);
  2226. }
  2227. } else {
  2228. if (!do_play) {
  2229. opt_output_file(opt);
  2230. } else {
  2231. opt_input_file(opt);
  2232. }
  2233. }
  2234. }
  2235. if (!do_play) {
  2236. /* file converter / grab */
  2237. if (nb_output_files <= 0) {
  2238. fprintf(stderr, "Must supply at least one output file\n");
  2239. exit(1);
  2240. }
  2241. if (nb_input_files == 0) {
  2242. prepare_grab();
  2243. }
  2244. } else {
  2245. /* player */
  2246. if (nb_input_files <= 0) {
  2247. fprintf(stderr, "Must supply at least one input file\n");
  2248. exit(1);
  2249. }
  2250. prepare_play();
  2251. }
  2252. ti = getutime();
  2253. av_encode(output_files, nb_output_files, input_files, nb_input_files,
  2254. stream_maps, nb_stream_maps);
  2255. ti = getutime() - ti;
  2256. if (do_benchmark) {
  2257. printf("bench: utime=%0.3fs\n", ti / 1000000.0);
  2258. }
  2259. /* close files */
  2260. for(i=0;i<nb_output_files;i++) {
  2261. if (!(output_files[i]->oformat->flags & AVFMT_NOFILE))
  2262. url_fclose(&output_files[i]->pb);
  2263. }
  2264. for(i=0;i<nb_input_files;i++)
  2265. av_close_input_file(input_files[i]);
  2266. return 0;
  2267. }