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.

2590 lines
82KB

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