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.

2572 lines
81KB

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